删除链表的倒数第N个节点

给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。

进阶:你能尝试使用一趟扫描实现吗?

 

 

#include <unordered_map>

using namespace std;

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) {
        ListNode *dummy_head = new ListNode(INT32_MIN, head);
        ListNode *first = dummy_head;
        ListNode *second = dummy_head;
        for (int i = 0; i < n + 1; ++i) {
            second = second->next;
        }
        while (second != nullptr) {
            second = second->next;
            first = first->next;
        }
        first->next = first->next->next;
        return dummy_head->next;
    }
};

 

posted on 2021-03-08 11:32  QzZq  阅读(60)  评论(0)    收藏  举报

导航