-
Notifications
You must be signed in to change notification settings - Fork 0
/
DoublyLinkedList.java
97 lines (81 loc) · 2.41 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
// Write a Program to implement doubly linked list and its operations.
public class Lab_2_Doubly_LinkedList {
Node head;
class Node {
int data;
Node prev;
Node next;
Node(int d) {
data = d;
}
}
public void insertFront(int data) {
Node newNode = new Node(data);
newNode.next = head;
newNode.prev = null;
if (head != null)
head.prev = newNode;
head = newNode;
}
public void insertAfter(Node prev_node, int data) {
if (prev_node == null) {
System.out.println("Previous node cannot be null");
return;
}
Node new_node = new Node(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 insertEnd(int data) {
Node new_node = new Node(data);
Node temp = head;
new_node.next = null;
if (head == null) {
new_node.prev = null;
head = new_node;
return;
}
while (temp.next != null)
temp = temp.next;
temp.next = new_node;
new_node.prev = temp;
}
void deleteNode(Node del_node) {
if (head == null || del_node == null) {
return;
}
if (head == del_node) {
head = del_node.next;
}
if (del_node.next != null) {
del_node.next.prev = del_node.prev;
}
if (del_node.prev != null) {
del_node.prev.next = del_node.next;
}
}
public void printlist(Node node) {
Node last = null;
while (node != null) {
System.out.print(node.data + "->");
last = node;
node = node.next;
}
System.out.println();
}
public static void main(String[] args) {
Lab_2_Doubly_LinkedList doubly_linkedlist = new Lab_2_Doubly_LinkedList();
doubly_linkedlist.insertEnd(5);
doubly_linkedlist.insertFront(1);
doubly_linkedlist.insertFront(6);
doubly_linkedlist.insertEnd(9);
doubly_linkedlist.insertAfter(doubly_linkedlist.head, 11);
doubly_linkedlist.insertAfter(doubly_linkedlist.head.next, 11);
doubly_linkedlist.printlist(doubly_linkedlist.head);
doubly_linkedlist.deleteNode(doubly_linkedlist.head.next.next.next.next.next);
doubly_linkedlist.printlist(doubly_linkedlist.head);
}
}