-
Notifications
You must be signed in to change notification settings - Fork 267
/
DoublyLinkedList.java
116 lines (93 loc) · 2.34 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
// javac ListaDuplamenteEncadeada.java
// java ListaDuplamenteEncadeada
public class ListaDuplamenteEncadeada {
public static void main(String[] args) {
LinkedList linkedList = new LinkedList();
linkedList.add(2);
linkedList.print();
linkedList.add(5);
linkedList.print();
linkedList.add(12);
linkedList.print();
linkedList.add(20);
linkedList.print();
linkedList.remove(12);
linkedList.print();
linkedList.remove(5);
linkedList.print();
}
}
class Node {
int data;
Node prev;
Node next;
public Node(int data, Node prev, Node next) {
this.data = data;
this.prev = prev;
this.next = next;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getPrev() {
return prev;
}
public void setPrev(Node prev) {
this.prev = prev;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
class LinkedList {
Node head = null;
Node tail = null;
public void add(int data) {
Node newNode = new Node(data, null, null);
if (this.head == null) {
this.head = newNode;
this.tail = newNode;
} else {
newNode.setPrev(this.tail);
newNode.setNext(null);
this.tail.setNext(newNode);
this.tail = newNode;
}
}
public void remove(int data) {
Node currentNode = this.head;
while (currentNode != null) {
if (currentNode.getData() == data) {
if (currentNode.getPrev() == null) {
this.head = currentNode.getNext();
currentNode.getNext().setPrev(null);
} else {
currentNode.getPrev().setNext(currentNode.getNext());
currentNode.getNext().setPrev(currentNode.getPrev());
}
}
currentNode = currentNode.getNext();
}
}
public void print() {
System.out.println("Doubly Linked List");
Node currentNode = this.head;
while (currentNode != null) {
if (currentNode.getPrev() == null) {
System.out.print("None ");
}
System.out.print("<---> | " + currentNode.getData() + " | ");
if (currentNode.getNext() == null) {
System.out.print("<---> None");
}
currentNode = currentNode.getNext();
}
System.out.println("\n===================================================");
}
}