-
Notifications
You must be signed in to change notification settings - Fork 0
/
DlinkedList.java
93 lines (81 loc) · 1.9 KB
/
DlinkedList.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
package com.company;
class DNode{
DNode next;
DNode prev;
int data;
DNode(int d){
this.data = d;
}
}
class DLinkedList{
DNode head;
public void add(int data){
DNode node = new DNode(data);
if(head ==null){
head = node;
return;
}
DNode current = head;
while(current.next != null){
current = current.next;
}
current.next = node;
node.prev = current;
}
public void addAtHead(int data){
DNode newhead = new DNode(data);
newhead.next = head;
head = newhead;
}
public void addAtTail(int data){
add(data);
}
public void print(){
DNode tail = head;
while(tail.next != null){
System.out.println(tail.data);
tail = tail.next;
}
System.out.println(tail.data);
}
public void printReverse(){
DNode node = head;
while(node.next != null){
node = node.next;
}
while(node != head){
System.out.println(node.data);
node = node.prev;
}
System.out.println(head.data);
}
public void reverseList(){
DNode temp = head;
DNode newhead = head;
while(temp != null){
DNode pre = temp.prev;
temp.prev = temp.next;
temp.next = pre;
newhead = temp;
temp = temp.prev;
}
while(newhead != null){
System.out.println(newhead.data);
newhead = newhead.next;
}
}
}
class Dlinked {
public static void main(String[] args) {
DLinkedList dl = new DLinkedList();
dl.add(13);
dl.add(16);
dl.add(56);
dl.add(78);
dl.print();
System.out.println();
dl.printReverse();
System.out.println();
dl.reverseList();
}
}