-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathq2p3.java
More file actions
95 lines (82 loc) · 2 KB
/
Copy pathq2p3.java
File metadata and controls
95 lines (82 loc) · 2 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
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
public class q2p3{
public static void main(String[] args){
Node head = new Node(0);
int cnt = 10;
while(cnt > 0){
head.append(cnt--);
}
Node buf = head;
while(buf != null){
System.out.println(">>"+ buf.value);
buf = buf.next;
}
//head.removeMid();
Node del = head.getNode(5);
head.removeMid2(del);
System.out.println("+++++++++++++++++++++++++++++++");
buf = head;
while(buf != null){
System.out.println(">>"+ buf.value);
buf = buf.next;
}
}
}
class Node{
public Node next = null;
public int value;
public Node(int value){
this.value = value;
}
public void append(int value){
Node end = new Node(value);
Node previous = this;
while(previous.next != null){
previous = previous.next;
}
previous.next = end;
}
public Node getNode(int k){
Node ans = this;
int n = 0;
while(ans != null){
if(n++ == k)
return ans;
ans = ans.next;
}
System.out.println("no such index");
return null;
}
//
//
// A: in this method, we know the head address before.
public void removeMid(){
Node ptr1 = this;
Node ptr2 = this;
Node pre1 = this;
while(ptr2.next != null){
if(ptr2.next == null)
break;
else if(ptr2.next.next == null){
break;
}
ptr2 = ptr2.next.next;
pre1 = ptr1;
ptr1 = ptr1.next;
}
pre1.next = ptr1.next;
}
// T: O(1)
// S: O(1)
// A:
public void removeMid2(Node pos){
if(pos == null)
return;
if(pos.next == null){
pos = null;
return;
}
Node buf= pos.next;
pos.value = buf.value;
pos.next = buf.next;
}
}