-
Notifications
You must be signed in to change notification settings - Fork 4
/
Solution.java
81 lines (57 loc) · 1.81 KB
/
Solution.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
public class Solution {
private static class MyNode {
MyNode next;
int val;
MyNode(int val) {
this.val = val;
}
@Override
public String toString() {
MyNode current = this;
StringBuilder sb = new StringBuilder();
while (current != null) {
sb.append(current.val).append(",");
current = current.next;
}
return sb.toString();
}
}
private static MyNode remove(MyNode head, int k) {
if (head == null)
return null;
if (k < 0)
return null;
MyNode current = head;
MyNode nodeToRemove = null;
MyNode previousOfNodeToRemove = null;
int offset = 0;
while (current != null) {
if (offset == k)
nodeToRemove = head;
else if (offset > k)
nodeToRemove = nodeToRemove.next;
if (offset == k + 1)
previousOfNodeToRemove = head;
else if (offset > k + 1)
previousOfNodeToRemove = previousOfNodeToRemove.next;
current = current.next;
offset++;
}
if (previousOfNodeToRemove == null && nodeToRemove == null)
return head;
if (previousOfNodeToRemove == null)
return head.next;
previousOfNodeToRemove.next = nodeToRemove.next;
return head;
}
public static void main(String[] args) {
MyNode head = new MyNode(1);
head.next = new MyNode(2);
head.next.next = new MyNode(3);
head.next.next.next = new MyNode(4);
head.next.next.next.next = new MyNode(5);
System.out.println(head);
head = remove(head, 2);
System.out.println(head);
}
}