forked from aswinkumarrk/data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDoublyLinkedList.java
More file actions
105 lines (83 loc) · 2.34 KB
/
DoublyLinkedList.java
File metadata and controls
105 lines (83 loc) · 2.34 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
package com.geeksforgeeks.linkedlist;
public class DoublyLinkedList {
Node head;
class Node {
int data;
DoublyLinkedList.Node next;
int size;
DoublyLinkedList.Node prev;
public Node(int data) {
this.data = data;
}
public Node() {
}
}
public void insert(int data) {
// Creating the new Node
Node newNode = new Node(data);
//Setting the next of newNode to head, as this is insert in front and prev = null;
newNode.next = head;
newNode.prev = null;
if (head != null) {
head.prev = newNode;
}
head = newNode;
}
public void append(int data) {
// Creating the new Node
Node newNode = new Node(data);
newNode.next = null;
if (head == null) {
newNode.next = head;
head = newNode;
return;
}
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
newNode.prev = temp;
}
public void printList(Node head) {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + ",");
temp = temp.next;
}
System.out.println();
}
public void reverseDoublyLinkedList(Node head) {
Node current = head;
Node temp = null;
while (current != null) {
temp = current.prev;
current.prev = current.next;
current.next = temp;
current = current.prev;
}
//Check for the case when empty list, or list with 1 node
if (temp != null) {
head = temp.prev;
}
printList(head);
}
public static void main(String[] args) {
DoublyLinkedList util = new DoublyLinkedList();
util.insert(5);
util.insert(4);
util.insert(3);
util.insert(2);
util.insert(1);
util.printList(util.head);
util = new DoublyLinkedList();
util.append(1);
util.append(2);
// util.append(3);
// util.append(4);
// util.append(5);
util.printList(util.head);
System.out.println("===========Reverse Doubly Linked List=================");
util.reverseDoublyLinkedList(util.head);
}
}