-
Notifications
You must be signed in to change notification settings - Fork 28
/
DoublyLinkedList.java
97 lines (73 loc) · 1.71 KB
/
DoublyLinkedList.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
90
91
92
93
94
95
96
97
package ds_002_linkedlists;
public class DoublyLinkedList {
private DCell SENTINEL_BEGIN;
private DCell SENTINEL_END;
private int size;
public DoublyLinkedList() {
SENTINEL_BEGIN = new DCell();
SENTINEL_END = new DCell();
SENTINEL_BEGIN.next = SENTINEL_END;
SENTINEL_END.prev = SENTINEL_BEGIN;
}
public DCell find(int value) {
DCell before = SENTINEL_BEGIN;
while(before.next.value != value && before.next != SENTINEL_END) {
before = before.next;
}
if(before.next.value == value) {
return before.next;
}
return null;
}
public void addFront(int value) {
addAfter(SENTINEL_BEGIN, value);
}
public void addBottom(int value) {
addBefore(SENTINEL_END, value);
}
public void addAfter(int ref, int value) {
DCell newCell = new DCell(value);
DCell refCell = this.find(ref);
if(refCell != null) {
refCell.addAfter(newCell);
size++;
}
}
public void addAfter(DCell refCell, int value) {
DCell newCell = new DCell(value);
if(refCell != null) {
refCell.addAfter(newCell);
size++;
}
}
public void addBefore(DCell refCell, int value) {
DCell newCell = new DCell(value);
if(refCell != null) {
refCell.addBefore(newCell);
size++;
}
}
public void remove(int value) {
DCell r = this.find(value);
if(r != null) {
r.remove();
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(DCell current = SENTINEL_BEGIN.next; current != SENTINEL_END; current = current.next) {
System.out.printf("%2d ", current.value);
}
System.out.printf("\n");
}
}