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.
public ListNode removeNthFromEnd(ListNode head, int n) {
// Start typing your Java solution below
// DO NOT write main() function
if (n < 1 || null == head) {
return head;
}
ListNode pre = head;
int i = 0;
for (i = 1; i <= n && null != pre; i++) {
pre = pre.next;
}
ListNode last = head;
ListNode preLast = null;
while (null != pre) {
pre = pre.next;
preLast = last;
last = last.next;
}
if (null != preLast) {
preLast.next = last.next;
} else if (i == n + 1) {
return head.next;
} else {
return head;
}
return head;
}