删除链表的倒数第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; } };
浙公网安备 33010602011771号