您的位置:首页 > Web前端 > Node.js

LeetCode Remove Nth Node From End of List

2015-02-12 00:58 316 查看
链接: 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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 链表