-
Notifications
You must be signed in to change notification settings - Fork 58
/
doubly_linkedlist_insertion.java
155 lines (131 loc) · 3.37 KB
/
doubly_linkedlist_insertion.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
package Linkedlist;
public class doubly_linkedlist_insertion {
Node head=null;
Node tail=null;
public class Node{
int data;
Node next;
Node prev;
Node(int data)
{
this.data=data;
this.next=null;
this.prev=null;
}
}
//inserting in the start
public void insertion(int data)
{
Node newNode=new Node(data);
newNode.next=null;
newNode.prev = null;
if(head==null)
{
head=newNode;
tail=newNode;
head.prev=null;
tail.next=null;
}
else
{
newNode.next=head;
head.prev=newNode;
head=newNode;
newNode.prev=null;
}
}
//inserting in the last
public void insertEnd(int data)
{
Node newNode=new Node(data);
Node curNode=head;
if(head==null)
{
head=newNode;
tail=newNode;
head.next=null;
return;
}
while(curNode.next!=null)
{
curNode=curNode.next;
}
newNode.next=null;
curNode.next=newNode;
newNode.prev=curNode;
}
//insertion at the given position
public void insertAtPos(int data,int pos)
{
Node newNode=new Node(data);
Node curNode=head;
if(head==null)
{
head=newNode;
head.next=null;
tail.next=null;
return;
}
if(pos < 1) {
System.out.print("\nposition should be >= 1.");
}
else if(pos==1)
{
newNode.next = head;
head.prev = newNode;
head = newNode;
}
else
{
for(int i = 1; i < pos-1; i++) {
if(curNode != null) {
curNode = curNode.next;
}
}
}
if(curNode != null) {
newNode.next = curNode.next; //for previous link
newNode.prev=curNode;
curNode.next=newNode;
if(newNode.next != null)
newNode.next.prev = newNode;
} else {
System.out.print("\nThe previous node is null.");
}
}
public void print()
{
Node curNode=head;
if(head==null)
{
System.out.println("list is empty");
}
while(curNode!=null)
{
System.out.print("<--"+curNode.data+"-->");
curNode=curNode.next;
}
System.out.print("Null");
}
public static void main(String args[])
{
doubly_linkedlist_insertion list=new doubly_linkedlist_insertion();
System.out.print("Insertion at the beginning:");
System.out.print("\n");
list.insertion(2);
list.insertion(3);
list.insertion(4);
list.insertion(5);
list.print();
System.out.print("\n \nInsertion at the end:");
System.out.print("\n");
list.insertEnd(2);
list.insertEnd(7);
list.insertEnd(8);
list.print();
System.out.print("\n \nInsertion at the given pos:");
System.out.print("\n");
list.insertAtPos(17,3);
list.print();
}
}