描述
Sort a linked list in O(nlogn) time using constant space complexity.
Sort a linked list in O(nlogn) time using constant space complexity.
#include<iostream>
#include<vector>;
using namespace std;
struct node
{
int data;
node *next;
};
node *CreateNode(int a[], int n)
{
if (n <= 0) return NULL;
node *head = new node();
head->data = a[0];
node *p = head;
for (int i = 1; i < n; i++)
{
node *q = new node();
q->data = a[i];
p->next = q;
p = q;
}
p->next = NULL;
return head;
}
void DisplayNode(node *head)
{
node *p = head;
while (p)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
void DeleteNode(node *head)
{
node *p = head;
while (head)
{
head = p->next;
delete p;
p = head;
}
}
node *MergeSort(node *head1, node *head2)
{
if (head1 == NULL) return head2;
if (head2 == NULL) return head1;
node *p = head1;
node *q = head2;
node *res=NULL;
node *result=NULL;
//===
if (p->data < q->data)
{
result = p;
p = p->next;
}
else
{
result = q;
q = q->next;
}
//===
res = result;
while (p&&q)
{
if (p->data < q->data)
{
res->next = p;
res = p;
p = p->next;
}
else
{
res->next = q;
res = q;
q = q->next;
}
}
if (p)
res->next = p;
if (q)
res->next = q;
head1 = NULL;
head2 = NULL;
return result;
}
node *SortList(node *&head)
{
if (head == NULL||head->next==NULL)
return head;
node *slow = head;
node *fast = head;
while (fast->next != NULL&&fast->next->next != NULL)
{
slow = slow->next;
fast = fast->next->next;
}
node *mid = slow->next;
slow->next = NULL;
node *list1 = SortList(head);
node *list2 = SortList(mid);
node *res = MergeSort(list1, list2);
return res;
}
int main()
{
const int n =8;
int a[n] = { -4, 0, 15, 17, 28, 32,-4,90 };
node *head = CreateNode(a, n);
node *res = SortList(head);
DisplayNode(res);
}