Given a linked list, remove the nth node from the end of list and return its head.
** Notice**
The minimum number of nodes in list is n.
Example
Given linked list: 1->2->3->4->5->null, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5->null.
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param head: The first node of linked list.
* @param n: An integer.
* @return: The head of linked list.
*/
ListNode removeNthFromEnd(ListNode head, int n) {
// write your code here
if (head == null) return null;
ListNode p1 = head;
ListNode p2 = head;
ListNode prev = null;
int i = 0;
while (i < n) {
p1 = p1.next;
i++;
}
while (p1 != null) {
prev = p2;
p2 = p2.next;
p1 = p1.next;
}
if (prev == null) {
head = head.next;
return head;
}
prev.next = p2.next;
return head;
}
}
/*
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if (n <= 0) {
return null;
}
// add one more to the list, then when the while loop ends, get the
// preDelete node right away
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode preDelete = dummy;
for (int i = 0; i < n; i++) {
if (head == null) {
return null;
}
head = head.next;
}
while (head != null) {
head = head.next;
preDelete = preDelete.next;
}
preDelete.next = preDelete.next.next;
return dummy.next;
}
}
*/