/**
* 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 = new ListNode(0);
dummyHead->next = head;
ListNode* pre = dummyHead;
ListNode* cur = head;
// pre与cur的索引插值保持为n 初始时pre为0,cur为1
while((--n)){
// cur先单独移动n个单位,如果n=1那么就不用移动了
cur = cur->next;
}
// cur直接移动到最后一个结点,此时pre->next就是要删除的结点
while(cur->next!=NULL){
pre = pre->next;
cur = cur->next;
}
// 删除
ListNode* tmp = pre->next;
pre->next = tmp->next;
delete tmp;
return dummyHead->next;
}
};
19. 删除链表的倒数第 N 个结点
最新推荐文章于 2024-06-22 15:35:31 发布