-
Notifications
You must be signed in to change notification settings - Fork 0
/
LeetCode19.java
54 lines (47 loc) · 1.29 KB
/
LeetCode19.java
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
public class LeetCode19 {
public ListNode removeNthFromEnd(ListNode head, int n) {
int length = 0;
ListNode next = head;
while (next != null) {
length++;
next = next.next;
}
int index = length - n;
return removeNthFromEndRec(head, index);
}
private ListNode removeNthFromEndRec(ListNode head, int n) {
if (head == null) {
return null;
}
if (n == 0) {
return head.next;
} else {
return new ListNode(head.val, removeNthFromEndRec(head.next, n - 1));
}
}
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;
}
}
}
// Stolen 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) return head.next;
// while (fast.next != null) {
// fast = fast.next;
// slow = slow.next;
// }
// slow.next = slow.next.next;
// return head;
// }