问题描述
Sort a linked list using insertion sort.
思路分析
用插入排序对一个链表进行排序。
插入排序就是对于新的元素,将它插入到已排序的元素的合适位置。如果是在数组中,还需要移动元素,但是对于链表就没有这个必要了,所以非常适合链表。
我们设置一个新的头new_head,cur = head表示之前的结点已经排序,和一个寻找合适位置的pre结点。然后以cur为基准进行循环,对于大于cur->val的就保持原位置;小于cur->val的就要找到合适的位置链接上。用一个while找到合适的位置,然后用temp保存pre->next,重置pre->next,将cur->next从原序列里删除,然后将pre->next重新连接上,插删连三步。最后将pre重置即可。
代码
/**
* 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 || !head->next)
return head;
ListNode* new_head = new ListNode(0);
new_head->next = head;
ListNode* pre = new_head;
ListNode* cur = head;
while (cur){
if (cur->next && cur->next->val < cur->val){
//find little node and put it to right place
while (pre->next && pre->next->val < cur->next->val)
pre = pre->next;
//pust cur->next to pre->next and keep the list
ListNode* temp = pre->next;
pre->next = cur->next;
cur->next = cur->next->next;//take cur->next away
pre->next->next = temp;
//move pre back to the head;
pre = new_head;
}
else
cur = cur->next;
}
return new_head->next;
}
};
时间复杂度:
O(n2)
O
(
n
2
)
空间复杂度:
O(1)
O
(
1
)
反思
链表题思路要清晰。