LeetCode 19. 删除链表的倒数第 N 个结点
思路:
先翻转链表再删除第n个节点再翻转链表
删除第n个节点需要pre指向head节点再用cur记录删除节点的前一个节点
/**
* 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* reverse(ListNode* head) {
ListNode* res = new ListNode(0);
while (head) {
ListNode* temp = head ->next;
head ->next = res ->next;
res ->next = head;
head = temp;
}
return res ->next;
}
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* head_rev = reverse(head);
ListNode* pre = new ListNode(0);
pre ->next = head_rev;
ListNode* cur = pre;
n = n -1;
while (n --) cur = cur ->next;
cur->next = cur ->next ->next;
return reverse(pre ->next);
}
};

浙公网安备 33010602011771号