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

19. Remove Nth Node From End of List

2016-03-15 16:01 295 查看
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

题目说 one pass ; 那么,这样,用两个直指针; p先跑n步,然后q和p一起跑,那么p跑到最后,q就正好在倒数第n个上面了。

Calculate the length first, and then remove the nth from the beginning.

public ListNode removeNthFromEnd(ListNode head, int n) {
if(head == null)
return null;

//get length of list
ListNode p = head;
int len = 0;
while(p != null){
len++;
p = p.next;
}

//if remove first node
int fromStart = len-n+1;
if(fromStart==1)
return head.next;

//remove non-first node
p = head;
int i=0;
while(p!=null){
i++;
if(i==fromStart-1){
p.next = p.next.next;
}
p=p.next;
}

return head;
}


Use fast and slow pointers. The fast pointer is n steps ahead of the slow pointer. When the fast reaches the end, the slow pointer points at the previous element of the target element.

public ListNode removeNthFromEnd(ListNode head, int n) {
if(head == null)
return null;

ListNode fast = head;
ListNode slow = head;

for(int i=0; i<n; i++){
fast = fast.next;
}

//if remove the first node
if(fast == null){
head = head.next;
return head;
}

while(fast.next != null){
fast = fast.next;
slow = slow.next;
}

slow.next = slow.next.next;

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