-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSort List.cpp
More file actions
83 lines (83 loc) · 1.37 KB
/
Copy pathSort List.cpp
File metadata and controls
83 lines (83 loc) · 1.37 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
ListNode* GetMid(ListNode* head)
{
if (!head || !head->next)
return head;
ListNode* pSlow = head;
ListNode* pFast = head->next;
while (pFast != NULL)
{
if (pFast->next)
pFast = pFast->next->next;
else
break;
pSlow = pSlow->next;
}
return pSlow;
}
ListNode* MergeList(ListNode* head1, ListNode* head2)
{
if (!head1)
return head2;
if (!head2)
return head1;
if (head1 == head2)
return head1;
ListNode* pNode1 = head1;
ListNode* pNode2 = head2;
ListNode* pNode = NULL;
ListNode* pHead = NULL;
while (pNode1 && pNode2)
{
if (pNode1->val < pNode2->val)
{
if (pNode)
{
pNode->next = pNode1;
pNode = pNode->next;
}
else
{
pNode = pNode1;
pHead = pNode;
}
pNode1 = pNode1->next;
}
else
{
if (pNode)
{
pNode->next = pNode2;
pNode = pNode->next;
}
else
{
pNode = pNode2;
pHead = pNode;
}
pNode2 = pNode2->next;
}
}
while (pNode1)
{
pNode->next = pNode1;
pNode = pNode->next;
pNode1 = pNode1->next;
}
while (pNode2)
{
pNode->next = pNode2;
pNode = pNode->next;
pNode2 = pNode2->next;
}
return pHead;
}
ListNode *sortList(ListNode *head) {
if (!head || !head->next)
return head;
ListNode* pMid = GetMid(head);
ListNode* pTmp = pMid->next;
pMid->next = NULL;
ListNode* pNode1 = sortList(head);
ListNode* pNode2 = sortList(pTmp);
return MergeList(pNode1, pNode2);
}