Leetcode - 19. Remove Nth Node From End of List

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

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.

Do this in one pass

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 == nullptr)
            return head;

        ListNode dummy{-1, head}; // 创建dummy,便于解决删除首个元素的情况
        ListNode* p = &dummy;
        ListNode* q = &dummy;
        
        for(int i=0; i<n; ++i)
        {
            q = q->next;
        }
        
        while(q->next)
        {
            p = p->next;
            q = q->next;
        }
        
        ListNode* tmp = p->next;
        p->next = p->next->next;
        delete tmp;
        
        return dummy.next;
    }
};
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页