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

[LeetCode 题解]: Remove Nth Node From End of List

2014-06-17 14:58 435 查看
Given a linked list, remove the nth 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个元素,并返回修改后的链表。

要求: 只经过一次遍历完成上述操作。

经典面试题,找到一个链表的倒数第N个元素的衍伸。 在本题中需要额外的记录第N个元素的上一个元素,用于元素删除。

寻找链表的倒数第N个元素,设置两个指针,分别从链表的头部出发,一个先遍历N个元素, 然后两个指针同时向后遍历,当前一个指针到达链表的尾部时,后一个指针则到达第N个元素。

 /**
* 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 *pre,*first,*last;
ListNode ans(0);
pre=first=last=head;
ans.next=pre;
for(int i=0;i<n;i++)
first=first->next; //find faster pointer

while(first!=NULL)
{
first=first->next;
pre = last;
last=last->next;
}
pre->next = last->next;
if(last==head) return head->next;
else return ans.next;
}
};


转载请注明出处 http://www.cnblogs.com/double-win/ 谢谢!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: