LeetCode 19. Remove Nth Node From End of List
原题链接
简单
作者:
RecSys
,
2021-02-24 18:07:48
,
所有人可见
,
阅读 245
/**
* 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 *dummy=new ListNode(-1);//虚拟头节点
dummy->next=head;//虚拟头节点指向头节点
ListNode *first=dummy,*second=dummy; //定义两个指针 初始时都指向虚拟节点
for(int i=0;i<n;i++) first=first->next;//循环结束后first指向第n-1个节点
while(first->next)
{
first=first->next;
second=second->next;
}
second->next=second->next->next;//删除(skip)
return dummy->next;
}
};