-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDoublyLinkedList.java
More file actions
138 lines (103 loc) · 2.7 KB
/
Copy pathDoublyLinkedList.java
File metadata and controls
138 lines (103 loc) · 2.7 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
/*
* doubly linked list of integers
* (with dummy element)
*
* CSI2510 Algortihmes et Structures de Donnees
* www.uottawa.ca
*
* Robert Laganiere, 2017
*
*/
public class DoublyLinkedList<Type> {
private class Node {
public Type element;
public Node prev;
public Node next;
public Node(Type v, Node p, Node n) {
element = v;
prev = p;
next = n;
}
}
private Node head;
private int size;
// construct empty list
public DoublyLinkedList() {
head = new Node(null, null, null);
head.prev = head.next = head;
size = 0;
}
// get the list size
public int getSize() {
return size;
}
// add a new integer (most efficient)
public boolean add(Type value) {
Node newNode = new Node(value, head, head.next);
head.next.prev = newNode;
head.next = newNode;
size++;
return true;
}
// add a new integer (least efficient)
public boolean addOppositeSide(Type value) {
Node newNode = new Node(value, head.prev, head);
head.prev.next = newNode;
head.prev = newNode;
size++;
return true;
}
// search a node in the list, given an element.
// Returns -1 if it's not in the list
public Type search(Type value) {
Node n = head.next;
while (n != head && n.element != value) {
n = n.next;
}
if (n == head) {
return null;
}
return n.element;
}
// remove a given integer (first occurrence of)
public boolean searchAndRemove(Type value) {
Node n = head.next;
while (n != head && n.element != value) {
n = n.next;
}
if (n != head) {
n.prev.next = n.next;
n.next.prev = n.prev;
size--;
return true;
} else {
return false;
}
}
// remove element at a given index
public boolean removeAt(int index) {
if (index < 0 || index >= size) {
return false;
}
size--;
Node n = head.next;
for (int i = 0; i < index; i++) {
n = n.next;
}
n.prev.next = n.next;
n.next.prev = n.prev;
return true;
}
// return the first element of the list
public Type getFirst() {
return head.next.element;
}
// string representation
public String toString() {
StringBuffer s = new StringBuffer("");
for (Node node = head.next; node != head; node = node.next) {
s.append("[" + node.element + "]");
}
return s.toString();
}
}