Skip to content

Commit 0aecdb0

Browse files
authored
Merge pull request #680 from SidMay101/main
Doubly linked list Insertion at given position.cpp
2 parents 00c248c + dbbcce1 commit 0aecdb0

File tree

1 file changed

+119
-0
lines changed

1 file changed

+119
-0
lines changed
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
/* a Node of the doubly linked list */
5+
struct Node
6+
{
7+
int data;
8+
struct Node *next;
9+
struct Node *prev;
10+
Node(int x)
11+
{
12+
data = x;
13+
next = prev = NULL;
14+
}
15+
};
16+
17+
void addNode(Node *head, int pos, int data);
18+
19+
Node *insert(Node *head, int x)
20+
{
21+
if (head == NULL)
22+
{
23+
return new Node(x);
24+
}
25+
Node *n = new Node(x);
26+
27+
head->next = n;
28+
n->prev = head;
29+
head = n;
30+
return head;
31+
}
32+
33+
void printList(Node *head)
34+
{
35+
// The purpose of below two loops is
36+
// to test the created DLL
37+
Node *temp=head;
38+
if (temp != NULL) {
39+
40+
while (temp->next!=NULL)
41+
temp=temp->next;
42+
while (temp->prev!=NULL)
43+
temp = temp->prev;
44+
}
45+
while (temp != NULL)
46+
{
47+
printf("%d ",temp->data);
48+
temp=temp->next;
49+
}
50+
51+
cout << endl;
52+
}
53+
54+
int main()
55+
{
56+
int t;
57+
scanf("%d",&t);
58+
while(t--)
59+
{
60+
Node *head = NULL;
61+
Node *root = NULL;
62+
int n;
63+
scanf("%d",&n);
64+
for(int i=0;i<n;i++){
65+
int x;
66+
scanf("%d",&x);
67+
head = insert(head, x);
68+
if(root==NULL) root = head;
69+
}
70+
head = root;
71+
int pos,data;
72+
cin>>pos>>data;
73+
addNode(head, pos, data);
74+
printList(head);
75+
}
76+
return 0;
77+
}// } Driver Code Ends
78+
79+
80+
/* a Node of the doubly linked list
81+
struct Node
82+
{
83+
int data;
84+
struct Node *next;
85+
struct Node *prev;
86+
Node(int x) { data = x; next = prev = NULL; }
87+
}; */
88+
89+
/* Function to insert into a Doubly Linked List */
90+
void addNode(Node *head, int pos, int data)
91+
{
92+
// Your code here
93+
Node *cur=head;
94+
Node *temp= new Node(data);
95+
if(head==NULL)
96+
{
97+
head=temp;
98+
return;
99+
}
100+
int count=0;
101+
while(count++ !=pos)
102+
{
103+
cur=cur->next;
104+
}
105+
if(cur->next==NULL)
106+
{
107+
cur->next=temp;
108+
temp->prev=cur;
109+
}
110+
else
111+
{
112+
cur->next->prev=temp;
113+
temp->next=cur->next;
114+
temp->prev=cur;
115+
cur->next=temp;
116+
}
117+
118+
119+
}

0 commit comments

Comments
 (0)