Sort a linked list using insertion sort.
题意:利用插入排序的思想实现链表排序;
思路:
从第二个指针开始,如果前一个指针p小于后一个指针q,则q直接连接到p后面;
否则,从头查找比q大的指针,然后进行插入;
[cpp] view plain copy
class Solution
{
public:
ListNode* insertionSortList(ListNode* head)
{
if (head==NULL || head->next==NULL)
{
return head;
}
ListNode* pre = new ListNode(-1);
pre->next = head;
ListNode* nHead = pre;
ListNode* p = head;
ListNode*q = head->next;
while (q)
{
if (q->val>=p->val)
{
p->next = q;
p = q;
q = p->next;
}
else
{
pre = nHead;
//从头遍历
while (pre->next->val<q->val)
{
pre = pre->next;
}
p->next = q->next;
q->next = pre->next;
pre->next = q;
q = p->next;
}
}
return nHead->next;
}
};