Poison

19. Remove Nth Node From End of List

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
// d -> 1 -> 2 -> 3 -> 4 -> 5, n = 2
// f
// s
ListNode dummyHead = new ListNode(-1, head);
ListNode first = head, second = dummyHead;
for (int i = 0; i < n; i++) {
first = first.next;
}
while (first != null) {
first = first.next;
second = second.next;
}

second.next = second.next.next;
return dummyHead.next;
}
}
Reference

19. Remove Nth Node From End of List
剑指 Offer II 021. 删除链表的倒数第 n 个结点