-
Notifications
You must be signed in to change notification settings - Fork 0
/
mergeSortedList.cpp
46 lines (45 loc) · 993 Bytes
/
mergeSortedList.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
/*
Merge two sorted lists A and B as one linked list
Node is defined as
struct Node
{
int data;
struct Node *next;
}
*/
Node* MergeLists(Node *headA, Node* headB)
{
// This is a "method-only" submission.
// You only need to complete this method
if(headA==nullptr && headB == nullptr)
return nullptr;
if(headA == nullptr)
return headB;
if(headB==nullptr)
return headA;
Node *me, *other, *ret, *temp;
if(headA->data <= headB->data) {
me = ret = headA;
other = headB;
}
else {
me = ret = headB;
other = headA;
}
while(1) {
if(me->next == nullptr) {
me->next = other;
return ret;
}
if(me->next->data <= other->data) {
me = me->next;
}
else {
temp = me->next;
me->next = other;
me = me -> next;
other = temp;
}
}
return ret;
}