[Link] https://leetcode.com/problems/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
20
21
22
23
24
25
26
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode zero = new ListNode(0);
zero.next = head;
ListNode tailHead, curNode;
curNode = tailHead = zero;
for(int i = 0; i < n; i++) curNode = curNode.next;
while(true) {
curNode = curNode.next;
if(curNode == null) break;
tailHead = tailHead.next;
}
tailHead.next = tailHead.next.next;
return zero.next;
}
}