xinyu04

导航

LeetCode 19 Remove Nth Node From End of List 链表节点删除+双指针

Given the head of a linked list, remove the \(n\)-th node from the end of the list and return its head.

Solution

首先在原链表开头设置新头节点,然后先用 \(fast\) 指针移动 \(n\) 个单位,此时再同时移动 \(slow,fast\) 指针直到 \(fast\) 到达尾部,这时候 \(slow\) 的下一个节点就是要删除的

点击查看代码
/**
 * 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) return NULL;
        // add extra head
        ListNode new_head(-1);
        new_head.next = head;
        
        // build 2 pointer: slow and fast
        ListNode *slow = &new_head, *fast = &new_head;
        
        // fast moves n steps
        for(int i=0;i<n;i++)fast = fast->next;
        
        // fast reaches the end
        while(fast->next){
            fast = fast->next;slow = slow->next;
        }
        ListNode *to_delete = slow->next;
        // delete n-th point
        slow->next = slow->next->next;
        
        delete to_delete;
        return new_head.next;
    }
};

posted on 2022-07-19 17:06  Blackzxy  阅读(15)  评论(0编辑  收藏  举报