-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathSortedLinkedList.java
70 lines (52 loc) · 1.29 KB
/
SortedLinkedList.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
package ds_002_linkedlists;
public class SortedLinkedList {
private Cell SENTINEL_BEGIN;
private Cell SENTINEL_END;
private int size;
public SortedLinkedList() {
SENTINEL_BEGIN = new Cell();
SENTINEL_END = new Cell();
SENTINEL_BEGIN.next = SENTINEL_END;
}
public void add(int value) {
Cell before = SENTINEL_BEGIN;
Cell newCell = new Cell(value);
while(before.next != SENTINEL_END && before.next.value < newCell.value) {
before = before.next;
}
if(before.next == SENTINEL_END) {
newCell.next = SENTINEL_END;
before.next = newCell;
} else {
newCell.next = before.next;
before.next = newCell;
}
size++;
}
public void remove(int value) {
Cell before = SENTINEL_BEGIN;
while(before.next.value < value && before.next != SENTINEL_END) {
before = before.next;
}
if(before.next.value == value) {
before.next = before.next.next;
size--;
}
}
public boolean isEmpty() {
return size == 0;
}
public int size() {
return size;
}
public void printList() {
System.out.print("List: ");
if(this.isEmpty()) {
System.out.print("EMPTY");
}
for(Cell current = SENTINEL_BEGIN.next; current != SENTINEL_END; current = current.next) {
System.out.printf("%2d ", current.value);
}
System.out.printf("\n");
}
}