-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmerge_sorted_lists.cpp
More file actions
138 lines (121 loc) · 2.26 KB
/
merge_sorted_lists.cpp
File metadata and controls
138 lines (121 loc) · 2.26 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
/*
You have been given two sorted linked list , merge both the linked list w/o using extra space so that
the resultin list is also a sorted one
*/
#include<iostream>
using namespace std ;
struct Node
{
int data;
Node *next;
Node(int data)
{
this->data=data;
this->next=NULL;
}
};
Node *input()
{
//number of nodes taking as input
int n;
cin>>n;
Node *head=NULL;
Node *tail=NULL;
for(int i=0;i<n;i++)
{
//this is to take input of n nodes
int x;
cin>>x;
Node *temp=new Node(x);
if(head==NULL)
{
head=temp;
tail=temp;
}
else
{
tail->next=temp;
tail=temp;
}
}
return head;
}
void printList(Node *head)
{
Node *p=head;
while(p!=NULL)
{
cout<<p->data<<" -> ";
p=p->next;
}
cout<<"\n";
}
Node *mergeList(Node *head1,Node *head2)
{
Node *p=head1;
Node *q=head2;
Node *r=NULL;
Node *head3=NULL;
while(p!=NULL && q!=NULL)
{
if(p->data<=q->data && r==NULL)
{
//this will be the head of the merged list
r=p;
p=p->next;
r->next=NULL;
head3=r;
}
else if(q->data<=p->data && r==NULL)
{
//this will be the head of the merged list
r=q;
q=q->next;
r->next=NULL;
head3=r;
}
else if(p->data<=q->data)
{
r->next=p;
p=p->next;
r=r->next;
r->next=NULL;
}
else
{
r->next=q;
q=q->next;
r=r->next;
r->next=NULL;
}
}
while(p!=NULL)
{
r->next=p;
p=p->next;
r=r->next;
r->next=NULL;
}
while(q!=NULL)
{
r->next=q;
q=q->next;
r=r->next;
r->next=NULL;
}
return head3;
}
int main()
{
Node *head1=NULL;
Node *head2=NULL;
head1=input();
head2=input();
cout<<"\nInputted list1 is : \n";
printList(head1);
cout<<"\nInputted list2 is : \n";
printList(head2);
Node *head3=NULL;
head3=mergeList(head1,head2);
printList(head3);
}