-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathDoubleLinkedList.java
More file actions
68 lines (60 loc) · 1.56 KB
/
DoubleLinkedList.java
File metadata and controls
68 lines (60 loc) · 1.56 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
class DoubleLinkedNode<T> {
int data;
DoubleLinkedNode<T> next;
DoubleLinkedNode<T> prev;
public DoubleLinkedNode(int data) {
this.data = data;
}
}
public class DoubleLinkedList {
private DoubleLinkedNode<Integer> head;
private DoubleLinkedNode<Integer> tail;
public void add(int data) {
DoubleLinkedNode<Integer> newNode = new DoubleLinkedNode<>(data);
if (head == null) {
head = tail = newNode;
} else {
tail.next = newNode;
newNode.prev = tail;
tail = newNode;
}
}
public void remove(int data) {
DoubleLinkedNode<Integer> current = head;
while (current != null && current.data != data) {
current = current.next;
}
if (current != null) {
if (current.prev != null) {
current.prev.next = current.next;
} else {
head = current.next;
}
if (current.next != null) {
current.next.prev = current.prev;
} else {
tail = current.prev;
}
}
}
public void printNode() {
DoubleLinkedNode<Integer> current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
public static void main(String[] args) {
DoubleLinkedList doubleLinkedList = new DoubleLinkedList();
doubleLinkedList.add(1);
doubleLinkedList.add(2);
doubleLinkedList.add(3);
doubleLinkedList.add(3);
doubleLinkedList.add(4);
doubleLinkedList.add(5);
doubleLinkedList.printNode();
doubleLinkedList.remove(3);
doubleLinkedList.printNode();
}
}