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

Remove Nth Node From End of List

2013-06-14 20:26 330 查看
Q: 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.

A: Two Pointers问题。用两个指针快的(p),慢的(cur),prev记录cur的前项。

p先走n-1步,然后cur,p同时走,prev记录前项。

注意:要考虑head node被删除的情况。

ListNode *removeNthFromEnd(ListNode *head, int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(!head||n==0)
return head;
int count = 0;
ListNode *prev,*cur,*p = head;

while(count<n-1)  //p go n-1 steps
{
count++;
p = p->next;
}

prev = NULL, cur = head;

while(p->next!=NULL)  //p and cur go together
{
prev = cur;
cur = cur->next;
p = p->next;
}

if(!prev)
return cur->next;
else{
prev->next = cur->next;
return head;
}

}


其实cur指针可以取代,只要prev和p。这种情况下p指针得先走n步。

public ListNode removeNthFromEnd(ListNode head, int n) {
// use two pointers,fast pointer forward n steps first
ListNode re=head,fast=head,slow=head;
for(int i=0;i<n;i++) fast=fast.next;  //faster 先走n步
if(fast==null) return head.next; //head node need to be removed。 att。
while(fast.next!=null){
fast=fast.next;
slow=slow.next;            //go together
}
slow.next=slow.next.next;   //slow相当于prev指针
return head;
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: