-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDoublyLinkedList1.java
More file actions
101 lines (99 loc) · 1.81 KB
/
DoublyLinkedList1.java
File metadata and controls
101 lines (99 loc) · 1.81 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
public class DoublyLinkedList1 {
class Node{
int data;
Node prev;
Node next;
Node(int data){
this.data=data;
this.next=null;
this.prev=null;
}
}
Node head=null;
Node tail=null;
public void addNode(int data) {
Node n=new Node(data);
if(head==null) {
head=n;
tail=n;
}
else {
tail.next=n;
n.prev=tail;
tail=n;
}
}
void insertAtstart(int data) {
Node n=new Node(data);
if(head==null) {
head=n;
tail=n;
}
else {
n.next=head;
head.prev=n;
head=n;
}
}
void insertAtend(int data) {
Node n=new Node(data);
if(head==null) {
head=n;
tail=n;
}
else {
tail.next=n;
n.prev=tail;
tail=n;
}
}
void insertAtAnyposition(int data,int pos) {
Node n=new Node(data);
Node temp=head;
Node ptr=temp.next;
if(head==null) {
head=n;
tail=n;
}
else {
for(int i=1; i<pos-1; i++) {
temp=ptr;
ptr=ptr.next;
}
temp.next=n;
n.prev=temp;
n.next=ptr;
ptr.prev=n;
}
}
public void display() {
Node temp=head;
if(head==null) {
System.out.println("List is Empty");
return;
}
while(temp !=null) {
System.out.print(temp.data+",");
temp=temp.next;
}
System.out.println();
}
public static void main(String[] args) {
DoublyLinkedList1 d1=new DoublyLinkedList1();
d1.addNode(10);
d1.addNode(20);
d1.addNode(30);
d1.addNode(40);
d1.addNode(50);
d1.display();
System.out.println("After Inserting The Element At First Position");
d1.insertAtstart(100);
d1.display();
System.out.println("After Inserting The Elements At End Position");
d1.insertAtend(200);
d1.display();
System.out.println("After Inserting The Elements At any Position");
d1.insertAtAnyposition(500,4);
d1.display();
}
}