-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathlist-sorted-merge.cpp
96 lines (82 loc) · 2.08 KB
/
list-sorted-merge.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// http://www.geeksforgeeks.org/merge-two-sorted-linked-lists/
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *next;
Node(int data) {
this->data = data;
this->next = NULL;
}
};
Node* mergeSortedLists(Node *head1, Node *head2);
Node* addNode(Node *head, int data);
void printList(Node *head);
Node* mergeSortedLists(Node *head1, Node *head2) {
if (head1 == NULL) return head2;
if (head2 == NULL) return head1;
Node *head = NULL;
while (head1 != NULL && head2 != NULL) {
if (head1->data < head2->data) {
head = addNode(head, head1->data);
head1 = head1->next;
}
else {
head = addNode(head, head2->data);
head2 = head2->next;
}
}
if (head1 == NULL)
while (head2 != NULL) {
head = addNode(head, head2->data);
head2 = head2->next;
}
else if (head2 == NULL)
while (head1 != NULL) {
head = addNode(head, head1->data);
head1 = head1->next;
}
return head;
}
Node* addNode(Node *head, int data) {
if (head == NULL)
return new Node(data);
Node *ptr = head;
while (ptr->next != NULL)
ptr = ptr->next;
ptr->next = new Node(data);
return head;
}
void printList(Node *head) {
if (head == NULL)
return;
while (head != NULL) {
cout<<head->data<<" ";
head = head->next;
}
}
int main() {
Node *head1 = NULL;
head1 = addNode(head1, 1);
head1 = addNode(head1, 3);
head1 = addNode(head1, 6);
head1 = addNode(head1, 8);
head1 = addNode(head1, 9);
Node *head2 = NULL;
head2 = addNode(head2, 2);
head2 = addNode(head2, 4);
head2 = addNode(head2, 5);
head2 = addNode(head2, 7);
head2 = addNode(head2, 10);
head2 = addNode(head2, 12);
cout<<"list 1: ";
printList(head1);
cout<<endl<<"list 2: ";
printList(head2);
head1 = mergeSortedLists(head1, head2);
cout<<endl<<"after merge: ";
printList(head1);
cout<<endl;
return 0;
}