-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathDoublyLinkedList.java
84 lines (73 loc) · 1.89 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
/*
* Doubly Linked List
*/
public class DoublyLinkedList {
public class Node {
int data;
Node next;
Node prev;
Node(int data) {
this.data = data;
this.next = null;
this.prev = null;
}
}
public static Node head;
public static Node tail;
public static int size;
public void addFirst(int data) {
Node nextNode = new Node(data);
size++;
if (head == null) {
head = tail = nextNode;
return;
}
nextNode.next = head;
head.prev = nextNode;
head = nextNode;
}
public void printFLL() {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
public void printLLL() {
Node temp = tail;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.prev;
}
System.out.println();
}
public void removeFLL() {
if (head == null) {
System.out.println("Doubly Linked List is Empty");
return;
}
if (size == 1) {
head.next = head.prev = null;
size--;
return;
}
head = head.next;
head.prev = null;
size--;
}
public static void main(String[] args) {
DoublyLinkedList dll = new DoublyLinkedList();
dll.addFirst(1);
dll.addFirst(2);
dll.addFirst(3);
dll.addFirst(4);
dll.addFirst(5);
System.out.println("LinkedList size: " + size); // LinkedList size: 5
dll.printFLL(); // 5 4 3 2 1
dll.printLLL(); // 1 2 3 4 5
dll.removeFLL();
dll.printFLL(); // 4 3 2 1
System.out.println("LinkedList size: " + size); // LinkedList size: 4
}
}