首页 > 其他 > 详细

【LeetCode】Insertion Sort List

时间:2014-09-06 13:34:23      阅读:247      评论:0      收藏:0      [点我收藏+]

Insertion Sort List

Sort a linked list using insertion sort.

 

本题是插入排序的链表版本。

传统数组版本做法就是两重循环,第一重是遍历所有元素,第二重是遍历已排序部分进行插入。

链表版本类似,在遍历每个元素过程中,遍历已排序部分进行插入。

 

上代码,代码参考九章算法解题站

class Solution {
public:
    ListNode *insertionSortList(ListNode *head) {
        ListNode *sortedHead = new ListNode(-1);
        while(head != NULL)
        {
            //保存head位置
            ListNode *temp = head->next;
            ListNode *cur = sortedHead;
            while(cur->next != NULL && cur->next->val < head->val)
            {
                cur = cur->next;
            }
            //插入
            head->next = cur->next;
            cur->next = head;
            //恢复head
            head = temp;
        }
        return sortedHead->next;
    }
};

bubuko.com,布布扣

 

【LeetCode】Insertion Sort List

原文:http://www.cnblogs.com/ganganloveu/p/3959331.html

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