- 删除链表的倒数第 N 个结点
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
/**
* 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) {
ListNode dummyHead(0, head);
ListNode* pre = &dummyHead;
while (n--) {
head = head->next;
}
while (head) {
head = head->next;
pre = pre->next;
}
pre->next = pre->next->next;
return dummyHead.next;
}
};