-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdoubleLL.java
More file actions
111 lines (97 loc) · 2.47 KB
/
Copy pathdoubleLL.java
File metadata and controls
111 lines (97 loc) · 2.47 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
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
public class doubleLL {
public class Node {
int data;
Node next;
Node prev;
public Node(int data) {
this.data = data;
this.next = null;
this.prev = null;
}
}
public static Node head;
public static Node tail;
public static int size;
// add first
public void addFirst(int data) {
Node newNode = new Node(data);
size++;
if (head == null) {
head = tail = newNode;
return;
}
newNode.next = head;
head.prev = newNode;
head = newNode;
}
// addLast
public void addLast(int data) {
Node newNode = new Node(data);
size++;
while (tail == null) {
head = tail = newNode;
return;
}
newNode.prev = tail;
tail.next = newNode;
tail = newNode;
}
// removeFirst
public int removeFirst() {
System.out.println("Removing first element of DLL..........");
if (head == null) {
System.out.println("DLL is empty");
return Integer.MIN_VALUE;
}
if (size == 1) {
int val = head.data;
head = tail = null;
size--;
return val;
}
size--;
int val = head.data;
head = head.next;
head.prev = null; // for single node this line will give error
return val;
}
// reverse
public void reverse() {
System.out.println("Reversing DLL..........");
Node curr = head;
Node prev = null;
Node next;
while (curr != null) {
next = curr.next;
curr.next = prev;
curr.prev = next;
prev = curr;
curr = next;
}
head = prev;
}
// print
public void print() {
Node temp = head;
System.out.print("null <-> ");
while (temp != null) {
System.out.print(temp.data + " <-> ");
temp = temp.next;
}
System.out.println("null");
}
public static void main(String[] args) {
doubleLL dll = new doubleLL();
dll.addFirst(3);
dll.addFirst(2);
dll.addFirst(1);
dll.addLast(4);
dll.print();
System.out.println("Size = " + dll.size);
dll.removeFirst();
dll.print();
System.out.println("Size = " + dll.size);
dll.reverse();
dll.print();
}
}