LeetCode - Algorithms - 19. Remove Nth Node From End of List

Java

Hint: Maintain two pointers and update one with a delay of n steps.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode fast = head, slow = head;
for(int i=0;i<n;i++)
fast = fast.next;
if (fast==null)
head = head.next;
else {
while(fast.next!=null) {
fast = fast.next;
slow = slow.next;
}
ListNode p = slow.next;
slow.next = p.next;
p.next = null;
}
return head;
}
}

Submission Detail

  • 208 / 208 test cases passed.
  • Runtime: 6 ms, faster than 98.72% of Java online submissions for Remove Nth Node From End of List.
  • Memory Usage: 38 MB, less than 100.00% of Java online submissions for Remove Nth Node From End of List.

ref