[Leetcode] remove nth node from the end of list 删除链表倒数第n各节点

时间:2023-03-10 06:39:54
[Leetcode] remove nth node from the end of list 删除链表倒数第n各节点

Given a linked list, remove the n th node from the end of list and return its head.

For example,

   Given linked list: 1->2->3->4->5, and n = 2.

   After removing the second node from the end, the linked list becomes 1->2->3->5.

Note: 
 Given n will always be valid.
Try to do this in one pass.

这题比较简单,使用快慢指针,找到倒数第n个结点的前驱即可,然后连接其前驱和后继即可,值得注意的是,两个while的条件之间的关系。代码如下:

 /**
* 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)
{
ListNode *nList=new ListNode(-);
nList->next=head;
ListNode *pre=nList;
ListNode *fast=head;
ListNode *slow=head;
int num=; while(num++<n)
{
fast=fast->next;
}
while(fast->next)
{
pre=pre->next;
slow=slow->next;
fast=fast->next;
}
pre->next=slow->next; return nList->next;
}
};