题目描述
使用插入排序对链表进行排序。
Sort a linked list using insertion sort.
思路
可以开辟一条新的链表来存储,并且这里也用到了虚拟头节点的技巧。没什么难的事情,主要就是对链表的操作要熟悉,要考虑到断链之后新链头的保存,然后这个复杂度是o(n^2)的,无他。
/**
* 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){
return head;
}
ListNode dummy(0);
ListNode* cur, *next, *p;
cur = head;
while(cur){
p = &dummy;
next = cur->next;
//cur->next;
while(p->next && cur->val > p->next->val){ //这个条件是比较需要琢磨清楚的。
p = p->next;
}
cur->next = p->next;
p->next = cur;
cur = next;
}
return dummy.next;
}
};