-
Notifications
You must be signed in to change notification settings - Fork 0
/
DoublyLL.java
83 lines (76 loc) · 1.77 KB
/
DoublyLL.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
public class DoublyLL {
public class Node{
int data;
Node next;
Node prev;
public Node(int data){
this.data = data;
this.next=null;
this.prev=null;
}
}
public static Node head;
public static Node tail;
public static int size;
//add
public void addFirst(int data){
Node newNode = new Node(data);
if(head==null){
head=tail=newNode;
return;
}
newNode.next = head;
head.prev = newNode;
head = newNode;
}
//remove
public int removeFirst(){
if(head==null){
System.out.println("Empty list");
return Integer.MIN_VALUE;
}
if(size==1){
int val = head.data;
head = null;
tail = null;
size-- ;
return val;
}
int val = head.data;
head = head.next;
head.prev = null;
return val;
}
public void reverse(){
Node curr = head;
Node prev = null;
Node next;
while(curr!=null){
next = curr.next;
curr.next = prev;
curr.prev = next;
prev = curr;
curr = next;
}
head = prev;
}
public void print(){
Node temp = head;
while(temp !=null){
System.out.print(temp.data + "<->");
temp = temp.next;
}
System.out.println("null");
}
public static void main(String[] args) {
DoublyLL dll = new DoublyLL();
dll.addFirst(3);
dll.addFirst(2);
dll.addFirst(1);
dll.print();
dll.removeFirst();
dll.print();
dll.reverse();
dll.print();
}
}