题目
Sort a linked list using insertion sort.
分析
实现链表的插入排序
注意:
- 程序入口的特殊输入判断处理!
- 节点的链接处理,避免出现断链!
AC代码
/**
* 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)
return head;
ListNode *p = head->next;
head->next = NULL;
//从头结点的下一节点开始,遍历插入排序
while (p)
{
//保存p节点的后续节点
ListNode *r = p->next;
//判断是否应插入到头结点
if (p->val < head->val)
{
p->next = head;
head = p;
}
else{
//寻找p节点应插入位置的前驱
ListNode *pre = head;
while (pre->next && pre->next->val <= p->val)
{
pre = pre->next;
}
p->next = pre->next;
pre->next = p;
}
//循环下一节点的插入
p = r;
}//while
return head;
}
};