-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmerge-two-linked-lists.cpp
72 lines (62 loc) · 1.3 KB
/
merge-two-linked-lists.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
#include <iostream>
using namespace std;
typedef struct Node {
int data;
Node *next;
} Node;
void insert(Node **head, int data) {
Node *temp = new Node();
temp->data = data;
temp->next = NULL;
if (head == NULL) {
*head = temp;
} else {
Node *lastnode = *head;
while (lastnode->next != NULL) {
lastnode = lastnode->next;
}
lastnode->next = temp;
}
return;
}
void printList(Node *head) {
struct Node *ptr = head;
std::cout << std::endl;
while (ptr != NULL) {
if (ptr->data)
std::cout << ptr->data << " ";
ptr = ptr->next;
}
std::cout << std::endl;
}
Node *merge_sorted_list(Node *a, Node *b) {
if (a == NULL)
return b;
if (b == NULL)
return a;
Node *result = new Node();
if (a->data < b->data) {
result = a;
result->next = merge_sorted_list(a->next, b);
} else {
result = b;
result->next = merge_sorted_list(a, b->next);
}
return result;
}
int main() {
int keys[] = {1, 2, 3, 4, 5, 6, 7};
int n = sizeof(keys) / sizeof(keys[0]);
Node *list1 = new Node();
Node *list2 = new Node();
int i;
for (i = 0; i < n / 2; i++) {
insert(&list1, keys[i]);
}
for (; i < n; i++) {
insert(&list2, keys[i]);
}
Node *merged_list = merge_sorted_list(list1, list2);
printList(merged_list);
return 0;
}