-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDoublyLinkedList.java
More file actions
72 lines (58 loc) · 1.37 KB
/
DoublyLinkedList.java
File metadata and controls
72 lines (58 loc) · 1.37 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
package list;
public class DoublyLinkedList {
private DoublyLinkedNode head;
public DoublyLinkedNode getHead() {
return this.head;
}
protected void setHead(DoublyLinkedNode head) {
this.head = head;
}
public boolean isHead(DoublyLinkedNode node) {
return this.head == node;
}
public void insertAtHead(Integer data) {
DoublyLinkedNode newNode = new DoublyLinkedNode(data);
newNode.setNextNode(this.head);
if (this.head != null) {
this.head.setPreviousNode(newNode);
}
this.head = newNode;
}
public int length() {
if (head == null)
return 0;
int length = 0;
DoublyLinkedNode curr = this.head;
while (curr != null) {
length += 1;
curr = curr.getNextNode();
}
return length;
}
public boolean isEmpty() {
return this.head == null;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
DoublyLinkedNode n = this.head;
while (n != null) {
sb.append("Node data: ");
sb.append(n);
sb.append("\n");
n = n.getNextNode();
}
return sb.toString();
}
public static void main(String[] args) {
DoublyLinkedList integers = new DoublyLinkedList();
integers.insertAtHead(5);
integers.insertAtHead(10);
integers.insertAtHead(2);
integers.insertAtHead(12);
integers.insertAtHead(19);
integers.insertAtHead(20);
new InsertionSorter().sort(integers);
System.out.println(integers);
}
}