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.
Solution 1 Iterative
1ms 7.59%
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head == null){
return head;
}
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode fast = dummy;
for(int i= 0; i < n; i++){
fast = fast.next;
}
ListNode slow = dummy;
while(fast.next != null){
slow = slow.next;
fast = fast.next;
}
slow.next = slow.next.next;
return dummy.next;
}
}
Solution2 Recursive
1ms 7.59%
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head == null){
return head;
}
ListNode dummy = new ListNode(-1);
dummy.next = head;
removeNode(dummy, n);
return dummy.next;
}
public int removeNode(ListNode root, int n){
if(root == null){
return 0;
}
int x = removeNode(root.next, n);
if(x == n){
root.next = root.next.next;
}
return x + 1;
}
}