forked from kbeathanabhotla/DSAAJ2-Answers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Chap03.question.12.SortedLinkedNode.java
89 lines (82 loc) · 2.4 KB
/
Chap03.question.12.SortedLinkedNode.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
82
83
84
85
86
87
88
89
//Chap03.question.12.SortedLinkedNode.java
public class MySortedLinkedList<E extends Comparable<? super E>> {
private LinkedNode head;
public int size() {
LinkedNode cur = head;
int size = 0;
while (cur != null) {
cur = cur.next;
size++;
}
return size;
}
public void print() {
LinkedNode cur = head;
while (cur != null) {
System.out.print(cur.data);
if (cur.next != null)
System.out.print("->");
}
}
public boolean contains(E x) {
if (x == null) return false;
LinkedNode cur = head;
while (cur != null) {
if (cur.data.compareTo(x) == 0) return true;
if (cur.data.compareTo(x) > 0) return false;
cur = cur.next;
}
return false;
}
public boolean add(E x) {
if (x == null) return false; // null is not allowed
if (head == null) {
head = new LinkedNode();
head.data = x;
return true;
}
LinkedNode dummy = new LinkedNode();
dummy.next = head;
while (dummy.next != null) {
if (dummy.next.data.equals(x)) return false;
if (dummy.next.data.compareTo(x) > 0) {
//add after dummy
LinkedNode t = dummy.next;
LinkedNode n = new LinkedNode();
n.data = x;
dummy.next = n;
n.next = t;
if (t == head) {
head = n;
}
return true;
}
dummy = dummy.next;
}
return false;
}
public boolean remove(E x) {
if (x == null) return false;
LinkedNode dummy = new LinkedNode();
dummy.next = head;
while (dummy.next != null) {
if (dummy.next.data.compareTo(x) < 0)
dummy = dummy.next;
else if (dummy.next.data.compareTo(x) == 0) {
LinkedNode t = dummy.next;
dummy.next = dummy.next.next;
if (t == head)
head = dummy.next;
return true;
} else {
assert dummy.next.data.compareTo(x) > 0;
return false;
}
}
return false;
}
class LinkedNode {
E data;
LinkedNode next;
}
}