Sort a linked list using insertion sort.
分析:此题要求在链表上实现插入排序。
思路:插入排序是一种O(n^2)复杂度的算法,基本想法就是每次循环找到一个元素在当前排好的结果中相对应的位置然后插进去,经过n次迭代之后就能得到排好序的结果。
可以这么做:建立一个helper头结点,然后依次将head链表中的结点有序的插入到helper链表中
代码:
/**
* 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 *helper=new ListNode(0);
ListNode *cur=head;
ListNode *pre;
while(cur){
ListNode *temp=cur->next;
pre=helper;
while(pre->next != NULL && pre->next->val < cur->val){
pre=pre->next;
}
cur->next=pre->next;
pre->next=cur;
cur=temp;
}
return helper->next;
}
};