-
Notifications
You must be signed in to change notification settings - Fork 0
/
Doublyll.java
83 lines (75 loc) · 1.82 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
import java.util.*;
class Doublyll{
private class Node{
int val;
Node next;
Node prev;
public Node(int val){
this.val=val;
}
public Node(int val, Node next, Node prev){
this.val=val;
this.next=next;
this.prev=prev;
}
}
private Node head;
private Node tail;
private int size;
public void insertFirst(int val){
Node node=new Node(val);
node.next=head;
node.prev=null;
if(head!=null)// To prevent null pointer exception
head.prev=node;
head=node;
}
public void insertLast(int val){
Node node= new Node(val);
Node last= head;
if(head!=null){
while(head.next!=null){
last=head.next;
}
}
head=node;
head.prev=null;
}
public void insert(int val, int index){
Node node= new Node(val);
if(index == 0){
insertFirst(val);
return;
}
if (index == (size-1)){
insertLast(val);
return;
}
Node temp= head;
int i=1;
while(i!=index){
temp= temp.next;
}
node.next=temp.next;
temp.next=node;
node.prev=temp;
if(node.next!=null)
node.next.prev=node;
}
public void display(){
Node node = head;
while(node!= null){
System.out.print(node.val + " -> ");
node= node.next;
}
System.out.println("Null");
}
public void revdisplay(){
Node node = tail;
while(node!= null){
System.out.print(node.val + " -> ");
node= node.prev;
}
System.out.println("Null");
}
}