首页 > 其他 > 详细

leetcode:Insertion Sort List

时间:2016-02-21 21:08:34      阅读:125      评论:0      收藏:0      [点我收藏+]

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;
    }
};

  

leetcode:Insertion Sort List

原文:http://www.cnblogs.com/carsonzhu/p/5205438.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!