鏈接: https://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/
給鏈表添加哨兵,使用差速指針找到待刪除節點的上一個節點,刪除即可 。
只需遍歷一次鏈表
/**
* 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 *nil=new ListNode(0);
nil->next=head;
head=nil;
ListNode *ft=head,*sl=head;
for(int i=0;i<n;i++)
{
ft=ft->next;
}
while(ft->next!=NULL)
{
ft=ft->next;
sl=sl->next;
}
nil=sl->next->next;
sl->next=nil;
return head->next;
}
};