-
Notifications
You must be signed in to change notification settings - Fork 168
/
Copy pathReverseDoubleLinkedList.java
82 lines (62 loc) · 1.23 KB
/
ReverseDoubleLinkedList.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
/*
Solved By: vanshbhasin157 (https://github.com/vanshbhasin157)
Modified By: Sandeep Ranjan (1641012352)
*/
class Node {
int data;
Node next, prev;
Node(int data) {
this.data = data;
next = prev = null;
}
}
class DLL {
private Node head;
public DLL() {
head = null;
}
void reverse() {
Node temp = null;
Node current = head;
while (current != null)
{
temp = current.prev;
current.prev = current.next;
current.next = temp;
current = current.prev;
}
if (temp != null) {
head = temp.prev;
}
}
public void insert(int data) {
Node new_node = new Node(data);
new_node.next = head;
if (head != null) {
head.prev = new_node;
}
head = new_node;
}
void printList() {
Node p = head;
while (p != null) {
System.out.print(p.data + " ");
p = p.next;
}
}
}
class ReverseDoubleLinkedList {
public static void main(String[] args) {
DLL list = new DLL();
list.insert(2);
list.insert(4);
list.insert(8);
list.insert(10);
System.out.println("Original linked list ");
list.printList();
list.reverse();
System.out.println("");
System.out.println("The reversed Linked List is ");
list.printList();
}
}