Given a linked list, remove the n-th node from the end of list and return its head.
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.
Follow up:
Could you do this in one pass?
solution 1: reverse LinkedList
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if (n < 1) {
return head;
}
head = reverse(head);
ListNode cur = head;
if (n == 1) {
return reverse(head.next);
}
while (n > 2) {
cur = cur.next;
n--;
}
cur.next = cur.next.next;
return reverse(head);
}
private ListNode reverse(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode prev = null;
while (head != null) {
ListNode next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
}
time: O(N)
space: O(1)
solution 2: two pointers
make a pointer ahead n nodes of the second pointer, each eteration we move both pointer s one step until the first node meets null
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode first = dummy;
ListNode second = dummy;
// Advances first pointer so that the gap between first and second is n nodes apart
for (int i = 1; i <= n + 1; i++) {
first = first.next;
}
// Move first to the end, maintaining the gap
while (first != null) {
first = first.next;
second = second.next;
}
second.next = second.next.next;
return dummy.next;
}
time: O(N)
space: O(1)