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.
/**
* 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) {
// Start typing your Java solution below
// DO NOT write main() function
int dist = 0;
ListNode left=head, right=head;
while(right.next!=null){
if(dist<n){
right=right.next;
dist++;
}
else{
right=right.next;
left=left.next;
}
}
if(left==head && dist<n)
head = head.next;
else
left.next = left.next.next;
return head;
}
}
------------------------------------------------------------------------------------------------------------------------------------------
LL's solution:
/**
* 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) {
// Start typing your Java solution below
// DO NOT write main() function
ListNode demi = new ListNode(0);
demi.next = head;
ListNode current = demi;
ListNode end = demi;
//move end to the Nth node from head
while(end.next!=null && n>0){
end = end.next;
n--;
}
if(n==0){
//move current and end concurrently until end reach the end of list
while(end.next!=null){
end = end.next;
current = current.next;
}
//remove current
current.next = current.next.next;
}
return demi.next;
}
}
Note:
Use a demi node to handle 'removing head' situation.