forked from pawanrajsingh2088/cpp-programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMerge Two Sorted Lists.cpp
More file actions
38 lines (36 loc) · 948 Bytes
/
Merge Two Sorted Lists.cpp
File metadata and controls
38 lines (36 loc) · 948 Bytes
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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
ListNode* t1 = list1;
ListNode* t2 = list2;
ListNode* dummyNode = new ListNode(-1);
ListNode* temp = dummyNode;
while(t1 != NULL && t2 != NULL){
if(t1 -> val < t2 -> val){
temp->next = t1;
temp = t1;
t1 = t1->next;
}
else{
temp->next = t2;
temp = t2;
t2 = t2->next;
}
}
if(t1) temp->next =t1;
else{
temp->next = t2;
}
return dummyNode->next;
}
};