-
Notifications
You must be signed in to change notification settings - Fork 0
/
Doubly linked list insertion at given position
120 lines (100 loc) · 2.01 KB
/
Doubly linked list insertion at given position
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
//Doubly linked list insertion at given position
import java.util.*;
class Node {
int data;
Node next;
Node prev;
Node(int data) {
this.data = data;
next = prev = null;
}
}
class DLinkedList {
Node newNode(Node head, int data) {
Node n = new Node(data);
if(head == null) {
head = n;
return head;
}
head.next = n;
n.prev = head;
head = n;
return head;
}
void printList(Node node) {
Node temp = node;
while(temp.next != null) {
temp = temp.next;
}
while(temp.prev != null) {
temp = temp.prev;
}
while(temp != null) {
System.out.print(temp.data+" ");
temp = temp.next;
}
System.out.println();
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
DLinkedList DLL = new DLinkedList();
int t = sc.nextInt();
while(t > 0) {
Node temp;
Node head = null;
Node root = null;
int n = sc.nextInt();
for(int i = 0; i < n; i++) {
int x = sc.nextInt();
head = DLL.newNode(head,x);
if(root == null) root = head;
}
head = root;
int pos = sc.nextInt();
int data = sc.nextInt();
GfG g = new GfG();
g.addNode(head,pos,data);
DLL.printList(head);
while(head.next != null) {
temp = head;
head = head.next;
}
t--;
}
}
}
class Node {
int data;
Node next;
Node prev;
Node(int data) {
this.data = data;
next = prev = null;
}
}
class GfG {
void addNode(Node head_ref, int pos, int data) {
Node newNode = new Node(data);
Node curr = head_ref;
int count = 0;
while(curr != null) {
if(count == pos) {
break;
}
count++;
curr = curr.next;
}
if(curr.next == null) {
curr.next = newNode;
newNode.prev = curr;
newNode.next = null;
}
else {
Node front = curr.next;
front.prev = newNode;
newNode.next = front;
newNode.prev = curr;
curr.next = newNode;
}
}
}