-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathDLL.java
149 lines (115 loc) · 3.28 KB
/
DLL.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
public class DLL {
Node head; // head of list
class Node {
int data;
Node prev;
Node next;
Node(int d) { data = d; }
}
public void push(int new_data)
{
Node new_Node = new Node(new_data);
new_Node.next = head;
new_Node.prev = null;
if (head != null)
head.prev = new_Node;
head = new_Node;
}
public void InsertBefore(Node next_node, int new_data)
{
if(next_node == null)
{
System.out.println("The given next node can not be NULL");
return;
}
Node new_node = new Node(new_data);
new_node.prev = next_node.prev;
next_node.prev = new_node;
new_node.next = next_node;
if(new_node.prev != null)
new_node.prev.next = new_node;
else
head = new_node;
}
public void InsertAfter(Node prev_Node, int new_data)
{
if (prev_Node == null) {
System.out.println("The given previous node cannot be NULL ");
return;
}
Node new_node = new Node(new_data);
new_node.next = prev_Node.next;
prev_Node.next = new_node;
new_node.prev = prev_Node;
if (new_node.next != null)
new_node.next.prev = new_node;
}
void append(int new_data)
{
Node new_node = new Node(new_data);
Node last = head;
new_node.next = null;
if (head == null) {
new_node.prev = null;
head = new_node;
return;
}
while (last.next != null)
last = last.next;
last.next = new_node;
new_node.prev = last;
}
public void printlist(Node node)
{
Node last = null;
System.out.println("Traversal in forward Direction");
while (node != null) {
System.out.print(node.data + " ");
last = node;
node = node.next;
}
System.out.println();
System.out.println("Traversal in reverse direction");
while (last != null) {
System.out.print(last.data + " ");
last = last.prev;
}
}
void deleteNode(Node del)
{
// Base case
if (head == null || del == null) {
return;
}
if (head == del) {
head = del.next;
}
if (del.next != null) {
del.next.prev = del.prev;
}
if (del.prev != null) {
del.prev.next = del.next;
}
return;
}
public static void main(String[] args)
{
DLL dll = new DLL();
dll.append(6);
// Insert at the beginning. So
dll.push(7);
dll.push(1);
//inert at end
dll.append(4);
dll.InsertAfter(dll.head.next, 8);
dll.InsertBefore(dll.head.next.next, 5);
System.out.println("Created DLL is: ");
dll.printlist(dll.head);
dll.deleteNode(dll.head);
System.out.print("\nList after deleting first node: ");
dll.printlist(dll.head);
dll.deleteNode(dll.head.next);
System.out.print("\nList after Deleting middle node: ");
dll.printlist(dll.head);
}
}