快速排序来排序链表,leetcode上竟然是超时了。。先贴上再说
#include<iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
};
int partition(ListNode*head, int beg, int end)
{
for (int i = 1; i < beg; i++)
head = head->next;
ListNode * p = head;
ListNode * q = p;
int cmp = p->val;
int tempswap;
int j = 0;
int pos = beg;
for (j = beg; j <= end; j++)
{
if (q->val < cmp)
{
p = p->next;
pos++;
tempswap = p->val;
p->val = q->val;
q->val = tempswap;
}
q = q->next;
}
tempswap = head->val;
head->val = p->val;
p->val = tempswap;
return pos;
}
void quicksort(ListNode * head, int beg, int end)
{
if (beg < end)
{
int part = partition(head, beg, end);
quicksort(head, beg, part - 1);
quicksort(head, part + 1, end);
}
}
int lengthList(ListNode * head)
{
int i = 0;
while (head != NULL)
{
head = head->next;
i++;
}
return i;
}
void printList(ListNode * head)
{
while (head != NULL)
{
cout << head->val;
head = head->next;
}
}
int main()
{
ListNode * head,*p,*q;
head = (ListNode*)malloc(sizeof(ListNode));
int input;
cin >> input;
head->val = input;
p = head;
q = head;
p->next = NULL;
while (cin >> input)
{
q = (ListNode*)malloc(sizeof(ListNode));
q->val = input;
p->next = q;
p = q;
p->next = NULL;
}
int length = lengthList(head);
quicksort(head, 1, length);
printList(head);
system("pause");
return 0;
}