-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmergeSort.cpp
More file actions
84 lines (70 loc) · 1.38 KB
/
Copy pathmergeSort.cpp
File metadata and controls
84 lines (70 loc) · 1.38 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <iostream>
using namespace std;
typedef int TYPE
struct node
{
TYPE data;
struct node *next;
};
void splitList(struct node* src, struct node** front, struct node** tail);
void mergeSort(struct node** root);
struct node* mergeHandle(struct node* list1, struct node* list2);
void mergeSort(struct node** root)
{
if (*root == NULL || *root->next == NULL)
return ;
struct node* head = *root;
struct node *first = NULL;
struct node* second = NULL;
splitList(root, first, second);
mergeSort(&first);
mergeSort(&second);
*root = mergeHandle(first, second);
}
void splitList(struct node*src, struct node** front, struct node** tail)
{
if (src == NULL)
return ;
struct node* slow = src;
struct node* fast = src->next;
while(fast && fast->next != NULL)
{
fast = fast->next;
if (fast != NULL)
{
slow = slow->next;
fast = fast->next;
}
}
*front = src;
*tail = slow->next;
slow->next = NULL;
}
struct node* mergeHandle(struct node* list1, struct node* list2)
{
if (list1 == NULL)
return list2;
if (list2 == NULL)
return list1;
struct node result;
struct node* p = result;
while(list1 && list2)
{
if (list1->data <= list2->data)
{
p->next = list1;
p = p->next;
list1 = list1->next;
}else
{
p->next = list2;
p = p->next;
list2 = list2->next;
}
}
if (list1)
p->next = list1;
else
p->next = list2;
return result->next;
}