1. 程式人生 > >19. Remove Nth Node From End of List(連結串列)

19. Remove Nth Node From End of List(連結串列)

https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/

題目:刪除倒數第n個節點(遍歷只能一趟)

思路:雙指標

例如:1->2->3->4->5,  n = 2
程式碼原理如下

t1的值     t1->next的值          t的值     n的值
0          1                    1         2
0          1                    2         1
0          1                    3
0 1 2 4 0 2 3 5 0 3 4 NULL 0 需要刪除的是:4 t1->next = t1->next->next 即可刪除4

程式碼如下

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
              ListNode
*t1 = new ListNode(0); ListNode *t = head; t1->next = head; head = t1; while(n || t) { t = t->next; t1 = (n?t1:t1->next); n = (n?n-1:n); } t1->next
= t1->next->next; //刪除倒數第n個節點 return head->next; } };