-
Notifications
You must be signed in to change notification settings - Fork 0
/
Merge_Two_Sorted_Linked_List.cpp
147 lines (130 loc) · 2.92 KB
/
Merge_Two_Sorted_Linked_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
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
142
143
144
145
146
147
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node *next;
Node(int x)
{
data = x;
next = NULL;
}
};
void printList(struct Node *head)
{
struct Node *temp = head;
while (temp != NULL)
{
cout << temp->data << ' ';
temp = temp->next;
}
cout << '\n';
}
// } 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.
class Solution
{
public:
Node *sortedMerge(Node *head1, Node *head2)
{
if (head1 == NULL)
return head2;
else if (head2 == NULL)
return head1;
Node *p = head1;
Node *q = head2;
Node *head = new Node(-1);
Node *dummy = head;
while (p != NULL && q != NULL)
{
if (p->data > q->data)
{
head->next = q;
head = q;
q = q->next;
}
else
{
head->next = p;
head = p;
p = p->next;
}
}
while (p != NULL)
{
head->next = p;
head = p;
p = p->next;
}
while (q != NULL)
{
head->next = q;
head = q;
q = q->next;
}
return dummy->next;
}
};
//{ Driver Code Starts.
// Driver program to test above functions
int main()
{
int T;
cin >> T;
cin.ignore();
while (T--)
{
int n1, n2, tmp;
Node *head1 = nullptr, *tail1 = nullptr;
Node *head2 = nullptr, *tail2 = nullptr;
string input1, input2;
getline(cin, input1); // Read the entire line for the LL1 elements
stringstream ss1(input1);
while (ss1 >> tmp)
{
Node *new_node = new Node(tmp);
if (head1 == nullptr)
{
head1 = new_node;
tail1 = new_node;
}
else
{
tail1->next = new_node;
tail1 = new_node;
}
}
getline(cin, input2); // Read the entire line for the LL2 elements
stringstream ss2(input2);
while (ss2 >> tmp)
{
Node *new_node = new Node(tmp);
if (head2 == nullptr)
{
head2 = new_node;
tail2 = new_node;
}
else
{
tail2->next = new_node;
tail2 = new_node;
}
}
Solution obj;
Node *head = obj.sortedMerge(head1, head2);
printList(head);
}
return 0;
}
// } Driver Code Ends