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.
Analysis:
1. The fast pointer points to the nth node after the head first.
2. Both of the fast and slow pointers start to move at the same speed, which is 1 node per time.
3. When the fast pointer points to null, the node pointed by the slow pointer should be the one that needs to be deleted.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode newhead = new ListNode(0);
newhead.next = head;
ListNode pslow = newhead;
ListNode slow = head;
ListNode fast = head;
if(head == null) return head;
for(int i=1; i<=n; i++) {
fast = fast.next;
}
while(fast != null) {
pslow = slow;
slow = slow.next;
fast = fast.next;
}
pslow.next = slow.next;
return newhead.next;
}
}
Update 02/03/2014:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head==null || n==0) return null;
ListNode newhead = new ListNode(-1);
newhead.next = head;
ListNode fast = head;
ListNode slow = newhead; // slow points to one element before the one which should be deleted!!!
for(int i=1; i<=n; i++) {
if(fast!=null) fast=fast.next;
else return null;
}
while(fast != null) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return newhead.next;
}
}