Sort a linked list in O(n log n) time using constant space complexity.
单链表排序问题,下面用插入排序的方法。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* sortList(ListNode* head) {
ListNode* p = new ListNode(0);
p->next = NULL;
ListNode *q = p;
if (head == NULL)
return head;
else
{
p->next = head;
head = head->next;
p->next->next = NULL;
}
while (head != NULL)
{
p = q;
while (p->next != NULL)
{
if (p->next->val >= head->val)
{
break;
}
p = p->next;
}
//insert head point node
ListNode *temp = head;
head = head->next;
temp->next = p->next;
p->next = temp;
}
return q->next;
}
};