Remove Nth Node From End of List

来源:互联网 发布:经济和信息化数据平台 编辑:程序博客网 时间:2024/05/21 09:04

Question: Given a linked list, remove the nth node from the end of list and return its head. 给定一个数值n, 从序列的末尾算起, 删除序列中的第n个节点.

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: 1. Given n will always be valid. 2. Try to do this in one pass. 1. 假设n总是有效的 2. 解决此问题只便利序列一次



Solution: Take advantage of fast pointer and slow pointer to traverse the list. Fast pointer is n ahead of slow pointer, when fast pointer gets to the end of list, the node that slow points is the one should be removed.


public class RemoveNodeFromEnd {
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head == null || head.next == null){
return null;
} else {
ListNode temp = new ListNode(0);
temp.next = head;
ListNode cur = temp;
ListNode slow = temp;

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

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

if(slow.next == null){
return null;
} else {
slow.next = slow.next.next;
}
return cur.next;
}
}
}

0 0
原创粉丝点击