/**
* 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();
dummyHead -> next = head;
ListNode* slow = head; //快慢指针
ListNode* fast = head;
ListNode* pre = new ListNode();
ListNode* next = new ListNode(); //存储当前遍历节点slow的前一个节点和后一个节点
while(fast){
if(n <= 0) { //slow开始移动
pre = slow;
slow = slow -> next;
next = slow -> next;
}
fast = fast -> next;
n--;
}
if(n == 0) { //若n为链表长度,则删除头结点
dummyHead -> next = head -> next;
delete head;
}
else{
pre -> next = next;
delete slow;
}
return dummyHead -> next;
}
};
<Talk is cheap, show me the code 37> LeetCode.19 删除链表的倒数第N个结点
最新推荐文章于 2024-09-10 23:34:31 发布