Leetcode 19. Remove Nth Node From End of List
You are given the head of a linked list, and an integer n
. Remove the nth node from the end of the 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.
Constraints:
sz
.1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
Q: Can we assume that the given linked list is always valid and non-empty? A: Yes, the constraints ensure that the list contains at least one node.
Q: What should we return if n
equals the length of the linked list?
A: We should remove the head of the list.
Q: Can n
be zero or out of range?
A: No, according to the constraints 1 <= n <= sz
.
fast
and slow
.fast
pointer n
steps ahead first.fast
and slow
simultaneously until fast
reaches the end of the list.slow
pointer.fast
and slow
to the dummy node.fast
n
steps forward.fast
and slow
simultaneously until fast.next
is null
.slow.next
to slow.next.next
to bypass the node to be removed.dummy.next
.// Definition for singly-linked list.
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
// Create a dummy node and point its next to head
ListNode dummy = new ListNode(0);
dummy.next = head;
// Initialize the fast and slow pointers
ListNode fast = dummy;
ListNode slow = dummy;
// Move the fast pointer n steps ahead
for (int i = 0; i < n; i++) {
fast = fast.next;
}
// Move both pointers until the fast.next is null
while (fast.next != null) {
fast = fast.next;
slow = slow.next;
}
// Remove the nth node from end
slow.next = slow.next.next;
// Return the head which dummy.next points to
return dummy.next;
}
}
fast
pointer moving n
steps and another traversal for both pointers).Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?