-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path55th_mergeDCLL.cpp
More file actions
141 lines (113 loc) · 2.35 KB
/
55th_mergeDCLL.cpp
File metadata and controls
141 lines (113 loc) · 2.35 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
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
//merge two doubly circular linked list
/*
I/P1 : 12 13 14 15 16
I/P2 : 40 50 60 70 80
O/P : 12 40 13 50 14 60 15 70 16 80
*/
#include<iostream>
using namespace std;
struct node
{
int data;
node *next;
node *prev;
node(int x)
{
data=x;
next=nullptr;
prev=nullptr;
}
};
node *append(node *head)
{
int x;
cout<<"Enter the data : ";
cin>>x;
node *temp=new node(x);
if(head==nullptr)
{
head=temp;
head->next=temp;
head->prev=temp;
}
else
{
node *p=head->prev;
head->prev=temp;
temp->next=head;
temp->prev=p;
p->next=temp;
}
cout<<"\n";
return head;
}
void display(node *head)
{
if(head==nullptr)
{
cout<<"List is empty.\n";
return;
}
node *p=head->next;
cout<<head->data<<" ";
while(p!=head)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<"\n";
}
node *mergelists(node *nhead,node *head1,node *head2)
{
node *p=head1->next;//point on first list
node *q=head2->next;//point on 2nd list
//merging the first two heads of list1 and list 2
//first I will join all the connections and then I will make the list circular at last
nhead=head1;
nhead->next=head2;
nhead->next->prev=nhead;
node *r=nhead->next;//pointing on new list
while(p!=head1)
{
node *temp1=p->next;
node *temp2=q->next;
//attaching the node from first list
r->next=p;
p->next->prev=r;
r=r->next;
//attaching the node from second list
r->next=q;
q->prev=r;
//making circular connection
nhead->prev=q;
r->next->next=nhead;
r->next->prev=r;
r=r->next;
p=temp1;
q=temp2;
}
return nhead;
}
int main()
{
int n;
cout<<"Enter number of nodes in the lists : ";
cin>>n;
node *head1=nullptr;
cout<<"List 1 : \n";
for(int i=1;i<=n;i++)
head1=append(head1);
cout<<"List 2 : \n";
node *head2=nullptr;
for(int i=1;i<=n;i++)
head2=append(head2);
cout<<"Original lists are : \n";
cout<<"List 1 : ";
display(head1);
cout<<"List 2 : ";
display(head2);
cout<<"Modified list is : \n";
node *nhead=nullptr;
nhead=mergelists(nhead,head1,head2);
display(nhead);
}