Remove Nth Node from End of List

LeetCode #19


Description:

Given a linked list, remove the nth node from the end of list and return its head.

Example:

For example,

   Given linked list: 1->2->3->4->5, and n = 2.

   After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.

Idea:

设两个指针 p,q,让 q 先走 n 步,然后 p 和 q 一起走,直到 q 走到尾节点,删除 p->next 即可。

Code:

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode dummy(-1);
        dummy.next=head;

        // 用dummy的好处是应付[1], n=1的情况。
        ListNode *ptr1=&dummy;
        ListNode *ptr2=&dummy;

        for(int i=0; i<n; ++i){
            ptr2=ptr2->next;
        }

        // check ptr2->next!=NULL,而不是ptr2!=NULL, 不然不好删除。
        while(ptr2->next!=NULL){
            ptr2=ptr2->next;
            ptr1=ptr1->next;
        }

        ptr1->next=ptr1->next->next;
        return dummy.next;

    }
};

results matching ""

    No results matching ""