LeetCode No19. 刪除連結串列的倒數第 N 個結點
阿新 • • 發佈:2022-04-22
題目
給你一個連結串列,刪除連結串列的倒數第 n 個結點,並且返回連結串列的頭結點。
示例 1:
輸入:head = [1,2,3,4,5], n = 2
輸出:[1,2,3,5]
示例 2:
輸入:head = [1], n = 1
輸出:[]
示例 3:
輸入:head = [1,2], n = 1
輸出:[1]
提示:
連結串列中結點的數目為 sz
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
進階:
你能嘗試使用一趟掃描實現嗎?
思路
基礎
先求出連結串列長度len,然後將倒數第n個數,替換為正數第len-n個數。
進階
其實就是想到的就是雙指標的做法,求倒數第n個節點,也就是說求到連結串列尾部為n的那個節點,那隻要定義兩個相差n的指標,大的指標到達連結串列尾部的時候,小的指標正好在倒數第n個節點上。
AC程式碼
基礎
點選檢視程式碼
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { private int getLen(ListNode head) { int len = 0; while( head.next!=null ) { head = head.next; len ++; } return len; } public ListNode removeNthFromEnd(ListNode head, int n) { int len = getLen(head); if( len+1==n ) { return head.next; } int m = len - n; int cnt = 0; ListNode node = head; while( cnt<m ) { node = node.next; cnt ++; } node.next = node.next.next; return head; } }
點選檢視程式碼
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode dummy = new ListNode(0, head); ListNode first = head; ListNode second = dummy; for (int i = 0; i < n; ++i) { first = first.next; } while (first != null) { first = first.next; second = second.next; } second.next = second.next.next; ListNode ans = dummy.next; return ans; } }