-
-
Notifications
You must be signed in to change notification settings - Fork 611
/
RemoveNthNodeFromEndofList.java
56 lines (47 loc) · 1.1 KB
/
RemoveNthNodeFromEndofList.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
55
56
package problems.easy;
import problems.utils.ListNode;
/**
* Created by sherxon on 1/4/17.
*/
public class RemoveNthNodeFromEndofList {
/**
* This is the recursive approach
*/
int n = 0;
public ListNode removeNthFromEnd(ListNode h, int nu) {
int size = 0;
ListNode head = h;
while (head != null) {
head = head.next;
size++;
}
int i = 0;
ListNode n = h;
ListNode p = h;
while (i < size - nu) {
i++;
p = n;
n = n.next;
}
if (i == 0) {
if (p.next == null) return null;
else h = p.next;
}
p.next = n.next;
return h;
}
public ListNode removeNthFromEndR(ListNode head, int n) {
if (head == null || head.next == null) return null;
this.n = n;
remove(head);
return this.n == 0 ? head.next : head;
}
void remove(ListNode x) {
if (x == null) return;
remove(x.next);
if (n == 0) {
x.next = x.next.next;
}
n--;
}
}