-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmerge2lists.cpp
More file actions
67 lines (53 loc) · 1.17 KB
/
Copy pathmerge2lists.cpp
File metadata and controls
67 lines (53 loc) · 1.17 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
/*
A singly-linked-list implementation
*/
#include <iostream>
using std::cout;
struct Node {
int val;
struct Node* next;
};
Node* appendNode(int val);
void printList(Node* node);
Node* mergeList(Node* L1, Node* L2);
int main()
{
// create and initialize two linked lists
Node* List1 = appendNode(0);
List1->next = appendNode(4);
List1->next->next = appendNode(6);
// 0->4->6
Node* List2 = appendNode(1);
List2->next = appendNode(2);
List2->next->next = appendNode(5);
List2->next->next->next = appendNode(7);
// 1->2->5->7
Node* mergedList = mergeList(List1, List2);
printList(mergedList);
}
Node* appendNode(int val) {
struct Node* temp = new Node;
temp->val = val;
temp->next = NULL;
return temp;
}
void printList(Node* node) {
while(node != NULL) {
cout << node->val << " ";
node = node->next;
}
}
Node* mergeList(Node* L1, Node* L2) {
if (!L1)
return L2;
if (!L2)
return L1;
if (L1->val < L2->val) {
L1->next = mergeList(L1->next, L2);
return L1;
}
else {
L2->next = mergeList(L1, L2->next);
return L2;
}
}