-
Notifications
You must be signed in to change notification settings - Fork 121
/
Merge_Two_Sorted_List.cpp
113 lines (100 loc) · 2.28 KB
/
Merge_Two_Sorted_List.cpp
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
// { Driver Code Starts
#include<iostream>
using namespace std;
/* Link list Node */
struct Node
{
int data;
struct Node *next;
Node(int x)
{
data = x;
next = NULL;
}
};
Node* sortedMerge(struct Node* a, struct Node* b);
/* Function to print Nodes in a given linked list */
void printList(struct Node *n)
{
while (n!=NULL)
{
cout << n->data << " ";
n = n->next;
}
cout << endl;
}
/* Driver program to test above function*/
int main()
{
int t;
cin>>t;
while(t--)
{
int n,m;
cin>>n>>m;
int data;
cin>>data;
struct Node *head1 = new Node(data);
struct Node *tail1 = head1;
for (int i = 1; i < n; ++i)
{
cin>>data;
tail1->next = new Node(data);
tail1 = tail1->next;
}
cin>>data;
struct Node *head2 = new Node(data);
struct Node *tail2 = head2;
for(int i=1; i<m; i++)
{
cin>>data;
tail2->next = new Node(data);
tail2 = tail2->next;
}
Node *head = sortedMerge(head1, head2);
printList(head);
}
return 0;
}
// } Driver Code Ends
/* Link list Node
struct Node {
int data;
struct Node *next;
Node(int x) {
data = x;
next = NULL;
}
};
*/
//Function to merge two sorted linked list.
Node* sortedMerge(Node* head1, Node* head2)
{
// code here
if(head1==NULL)return head2;
if(head2==NULL)return head1;
else{
Node* temp1 = head1;
Node* temp2 = head2;
Node* prev = NULL;
while(temp1!=NULL && temp2!=NULL){
if(temp1->data<=temp2->data){
prev = temp1;
temp1 = temp1->next;
}
else if(temp1->data>temp2->data){
Node* temp=temp2;
if(prev==NULL){
prev=temp;
head1=prev;
}
else prev->next = temp;
temp2=temp2->next;
temp->next=temp1;
prev=temp;
}
}
if(temp1==NULL)prev->next=temp2;
return head1;
}
}