-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDoublyLinkedList.java
99 lines (87 loc) · 2.68 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
package midterm;
public class DoublyLinkedList {
DoublyLinkedListNode head, tail;
public void addToHead(int info) {
if (isEmpty()) {
head = tail = new DoublyLinkedListNode(info);
} else {
head = new DoublyLinkedListNode(info, head, null);
head.next.prev = head;
}
}
public void addToTail(int info) {
if (isEmpty()) {
head = tail = new DoublyLinkedListNode(info);
} else {
tail.next = new DoublyLinkedListNode(info, null, tail);
tail = tail.next;
}
}
public void addAt(int index, int info) {
if (index == 0) {
addToHead(info);
} else if (index < 0) {
System.out.println("Invalid index! Index must greater than zero");
} else {
DoublyLinkedListNode temp = head;
for (int i = 1; i <= index && temp != null; i++, temp = temp.next);
if (temp == null) {
System.out.println("Invalid index!");
} else {
temp.prev = temp.prev.next = new DoublyLinkedListNode(info, temp, temp.prev);
}
}
}
public void deleteFromHead() {
if (isEmpty()) {
System.out.println("Nothing to delete!");
} else if (head == tail) {
head = tail = null;
} else {
head = head.next;
head.prev = null;
}
}
public void deleteFromTail() {
if (isEmpty()) {
System.out.println("Nothing to delete!");
} else if (head == tail) {
head = tail = null;
} else {
tail.prev.next = null;
tail = tail.prev;
}
}
public void deleteAt(int index) {
if (isEmpty()) {
System.out.println("Nothing to delete!");
} else if (index == 0) {
deleteFromHead();
} else {
DoublyLinkedListNode temp = head;
for (int i = 1; i <= index && temp != null; i++, temp = temp.next);
if (temp == tail) {
deleteFromTail();
} else if (temp == null) {
System.out.println("Invalid index!");
} else {
temp.prev.next = temp.next;
temp.next.prev = temp.prev;
}
}
}
public void printAllNode() {
if (isEmpty()) {
System.out.println("Notinh to print!");
} else {
DoublyLinkedListNode temp = head;
while (temp != null) {
System.out.println(temp.info);
temp = temp.next;
}
}
}
public boolean isEmpty() {
return head == null;
}
}