-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDoublyLinkedList.java
More file actions
117 lines (103 loc) · 2.09 KB
/
DoublyLinkedList.java
File metadata and controls
117 lines (103 loc) · 2.09 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
106
107
108
109
110
111
112
113
114
115
116
117
package technical;
public class DoublyLinkedList {
private Listnode head;
private Listnode tail;
private int length;
private class Listnode {
private Listnode pre;
private Listnode next;
private int data;
public Listnode(int data) {
this.data = data;
this.next = null;
this.pre = null;
}
}
public DoublyLinkedList() {
this.head = null;
this.tail = null;
this.length = 0;
}
public boolean isEmpty() {
return length == 0;
}
public int length() {
return length;
}
public Listnode deletefirst() {
Listnode temp=head;
if(head==tail) {
tail=null;
}else {
head.next.pre=null;
}
head=head.next;
temp.next=null;
return temp;
}
public Listnode deletelast() {
Listnode temp=head;
if(head==tail) {
head=null;
}else {
tail.pre.next=null;
}
tail=tail.pre;
temp.pre=null;
return temp;
}
public void insertatfirst(int value) {
Listnode newnode = new Listnode(value);
if (head == null) {
tail = newnode;
} else {
head.pre = newnode;
}
newnode.next = head;
head = newnode;
length++;
}
public void insertatlast(int value) {
Listnode newnode = new Listnode(value);
if (head == null) {
head = newnode;
} else {
tail.next = newnode;
}
newnode.pre = tail;
tail = newnode;
length++;
}
public void displayforward() {
if (head == null) {
return;
}
Listnode temp = head;
while (temp != null) {
System.out.print(temp.data + "-->");
temp = temp.next;
}
System.out.print("null");
}
public void displaybackward() {
if (tail == null) {
return;
}
Listnode temp = tail;
while (temp != null) {
System.out.print(temp.data + "-->");
temp = temp.pre;
}
System.out.print("null");
}
public static void main(String[] args) {
DoublyLinkedList dll = new DoublyLinkedList();
dll.insertatlast(1);
dll.insertatlast(13);
dll.insertatlast(23);
dll.insertatlast(55);
dll.insertatlast(63);
dll.displayforward();System.out.println();
dll.displaybackward();
}
}