-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathMergeTwoSortedLinkedLists.cpp
More file actions
58 lines (56 loc) · 1.27 KB
/
MergeTwoSortedLinkedLists.cpp
File metadata and controls
58 lines (56 loc) · 1.27 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
/* Link list Node
struct Node {
int data;
struct Node* next;
}; */
struct Node* New(int v)
{
struct Node* n = (struct Node*)malloc(sizeof(n));
n->next = NULL;
n->data = v;
return n;
}
struct Node* SortedMerge(struct Node* head1, struct Node* head2)
{
struct Node* head;
if(head1 && head2){
if(head1->data < head2->data){
head = New(head1->data);
head1 = head1->next;
}else{
head = New(head2->data);
head2 = head2->next;
}
}else{
if(head1){
head = New(head1->data);
head1 = head1->next;
}else if(head2){
head = New(head2->data);
head2 = head2->next;
}
}
struct Node* c = head;
while(head1 && head2){
if(head1->data < head2->data){
c->next = New(head1->data);
c = c->next;
head1 = head1->next;
}else{
c->next = New(head2->data);
c = c->next;
head2 = head2->next;
}
}
while(head1){
c->next = New(head1->data);
c = c->next;
head1 = head1->next;
}
while(head2){
c->next = New(head2->data);
c = c->next;
head2 = head2->next;
}
return head;
}