-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoveNthNodeFromEndOfList.java
More file actions
39 lines (36 loc) · 1.09 KB
/
RemoveNthNodeFromEndOfList.java
File metadata and controls
39 lines (36 loc) · 1.09 KB
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
31
32
33
34
35
36
37
38
39
import common.ListNode;
/*
* https://leetcode.com/problems/remove-nth-node-from-end-of-list/
*/
public class RemoveNthNodeFromEndOfList {
public ListNode removeNthFromEnd(ListNode head, int n) {
if (indexFromRight(head, n) == n) {
return head.next;
}
return head;
}
private int indexFromRight(ListNode node, int n) {
if (node.next == null) {
return 1;
}
int index = 1 + indexFromRight(node.next, n);
if (index == n + 1) {
if (n == 1) {
node.next = null;
} else {
node.next = node.next.next;
}
}
return index;
}
public static void main(String[] args) {
System.out.println(new RemoveNthNodeFromEndOfList().removeNthFromEnd(
new ListNode(1,
new ListNode(2,
new ListNode(3,
new ListNode(4,
new ListNode(5))))),
2
)); // 1,2,3,5
}
}