欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Remove Nth Node From End of List(C++)

程序员文章站 2022-07-01 18:11:39
remove nth node from end of list(c++) 。given a linked list, remove then-th node from the end of lis...

remove nth node from end of list(c++) 。given a linked list, remove then-th node from the end of list and return its head.

/**
* 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->next==null)
return null;
listnode *prev=head,*cur=head;
for(int i=0;i
cur=cur->next;
if(cur==null)
return head->next;
while(cur->next!=null)
{
cur=cur->next;
prev=prev->next;
}
prev->next=prev->next->next;
return head;
}
};