/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(!head) return nullptr;
if(head->next == nullptr && n == 1) return nullptr;
ListNode* dummy = new ListNode(0);
dummy->next = head;
ListNode *front = dummy, *back = dummy;
int i = 0;
while(i <= n) {
front = front->next;
i++;
}
while(front) {
front = front->next;
back = back->next;
}
back->next = back->next->next;
ListNode* res = dummy->next;
delete dummy;
return res;
}
};
LeetCode19. 删除链表的倒数第N个节点
最新推荐文章于 2020-09-19 22:01:29 发布