题目:用插入排序法将链表排序
分析:就是最简单的插入排序+链表操作,注意当节点最小的会插入到最前面的特殊情况即可。
答案:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
if (head == NULL || head->next == NULL)
return head;
ListNode *p = head->next;
head->next = NULL;
while (p != NULL)
{
ListNode *pNext = p->next; /*store the next node to be insert*/
ListNode *q = head;
if (p->val < q->val) /*node p should be the new head*/
{
p->next = q;
head = p;
}
else
{
while (q != NULL && q->next != NULL && q->next->val <= p->val)
q = q->next;
p->next = q->next;
q->next = p;
}
p = pNext;
}
return head;
}
};