qiaoxu123
3/4/2019 - 12:36 AM

19. Remove Nth Node From End of List

链表遍历题目。主要考虑使用双指针进行倒计时,保证两个指针的间隔正好是n即可。

//Runtime: 8 ms, faster than 100.00%
//Memory Usage: 9.7 MB, less than 54.37%

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* start = new ListNode(0);
        start->next = head;
        
        ListNode* fast = start;
        ListNode* slow = start;
        
        for(int i = 1;i <= n;++i)
            fast = fast->next;
        while(fast->next != NULL){
            fast = fast->next;
            slow = slow->next;
        }
        slow->next = slow->next->next;
        return start->next;
    }
};