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 alwaysbe valid.
Try to do this in onepass.
Java Solutions:
Via double points——fast and slow, the fast point first move to n nodes fromhead, then move both pointers one by one until the fast pointer reaches end. Nowthe slow pointer will point to nth node from the end.
/**
* 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)
return null;
ListNode fast=head;
int step=0;
while(step<n&&fast!=null){
step++;
fast=fast.next;
}
// the removed node is the head
if(fast==null){
return head.next;
}
ListNode pre=head;
ListNode slow=head;
// find the positon of the removed node, the slow node
while(fast!=null){
pre=slow;
slow=slow.next;
fast=fast.next;
}
// remove the node
pre.next=slow.next;
return head;
}
}