-
Notifications
You must be signed in to change notification settings - Fork 994
Expand file tree
/
Copy pathmergeTwoSortedList.cpp
More file actions
123 lines (92 loc) · 2.31 KB
/
Copy pathmergeTwoSortedList.cpp
File metadata and controls
123 lines (92 loc) · 2.31 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
// 3. link : [ https://leetcode.com/problems/merge-two-sorted-lists ]
#include<bits/stdc++.h>
using namespace std;
// node class
class ListNode{
public:
int val;
ListNode* next;
ListNode(int data){
this->val = data;
next = NULL;
}
};
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* temp1 = l1;
ListNode* temp2 = l2;
ListNode* tail = new ListNode(0);
ListNode* head = tail;
while(temp1 && temp2){
if(temp1->val <= temp2->val){
ListNode* newNode = new ListNode(temp1->val);
tail->next = newNode;
tail = newNode;
temp1 = temp1->next;
}else{
ListNode* newNode = new ListNode(temp2->val);
tail->next = newNode;
tail = newNode;
temp2 = temp2->next;
}
}
while(temp1){
ListNode* newNode = new ListNode(temp1->val);
tail->next = newNode;
tail = newNode;
temp1 = temp1->next;
}
while(temp2){
ListNode* newNode = new ListNode(temp2->val);
tail->next = newNode;
tail = newNode;
temp2 = temp2->next;
}
return head->next;
}
ListNode* takeInput(){
ListNode* head = NULL;
ListNode* tail = NULL;
int data;
while(cin >> data && data != -1){
ListNode* node = new ListNode(data);
if(head == NULL){
head = node;
tail = node;
}else{
tail->next = node;
tail = node;
}
}
return head;
}
void print(ListNode* head){
if(head == NULL)
return;
while(head){
cout << head->val << " ";
head = head->next;
}
cout << endl;
}
/*
1
1
1 3 4 5 6 -1
-2 -4 3 7 9 -1
-2 -4 1 3 3 4 5 6 7 9
*/
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int test;
cin >> test;
while(test--){
ListNode* l1 = takeInput();
ListNode* l2 = takeInput();
ListNode* head = mergeTwoLists(l1, l2);
print(head);
}
return 0;
}