//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.
public class Solution {
static class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public static void main(String[] args) {
ListNode a = new ListNode(1);
ListNode input = a;
for(int i = 0;i<1;i++){
ListNode temp = new ListNode(i+2);
a.next = temp;
a = a.next;
}
ListNode result = removeNthFromEnd(input,2);
while(result != null){
System.out.println(result.val);
result = result.next;
}
}
public static ListNode removeNthFromEnd(ListNode head, int n) {
ListNode result = head;
int count = 1;
while(head.next!=null){ //
count++;
head = head.next;
}
if(count == 1){ // ,
return null;
}
int timing = count-n;
if(timing == 0){ // 0,
result = result.next;
return result;
}
head = result;
for(int i = 1;i<timing;i++){ //
head = head.next;
}
head.next = head.next.next; //
return result;
}
}