-
Notifications
You must be signed in to change notification settings - Fork 207
Expand file tree
/
Copy pathSolution.java
More file actions
30 lines (25 loc) · 784 Bytes
/
Solution.java
File metadata and controls
30 lines (25 loc) · 784 Bytes
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
28
29
30
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode first = dummy;
ListNode second = dummy;
// Advance first pointer so that the gap between first and second is n nodes apart
for (int i = 0; i <= n; i++) {
first = first.next;
}
// Move first to the end, maintaining the gap
while (first != null) {
first = first.next;
second = second.next;
}
// Remove the nth node from the end
second.next = second.next.next;
return dummy.next;
}
}