19. Remove Nth Node From End of List
19. Remove Nth Node From End of List
題意
給定一個 linked list,跟一個數字 n
,移除 linked list 倒數第 n
個 node
限制
-
The number of nodes in the list is
sz
. -
1 <= sz <= 30
-
0 <= Node.val <= 100
-
1 <= n <= sz
思考
-
遍歷 linked list 到末端算出長度,再算出
長度 - n
後從頭開始執行長度 - n
次後抵達並移除該節點 -
One pass: 利用快慢指標
-
先將
fast
向前移動n
次 -
slow
從頭開始 -
將兩個指標向前移動直到
fast
抵達末端,此時slow
就會剛好在length - n
的位子
-
Solution
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if (!head->next) {
return nullptr;
}
auto fast = head;
while (n--) {
fast = fast->next;
}
if (!fast) {
return head->next;
}
auto slow = head;
while (fast->next) {
slow = slow->next;
fast = fast->next;
}
slow->next = slow->next->next;
return head;
}
};