Given a linked list, remove the nth node from the end of list and return its head.
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.
双指针, 注意remove首元素情况。
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) {
if(head == null) return null;
ListNode prev = null, cur = head, next = head;
while(n - 1 > 0) {
next = next.next;
n--;
}
while(next.next != null) {
prev = cur;
cur = cur.next;
next = next.next;
}
if(prev == null) return cur.next;
prev.next = prev.next.next;
return head;
}
}