首页 > 其他 > 详细

【LeetCode OJ】Insertion Sort List

时间:2014-03-13 11:22:39      阅读:365      评论:0      收藏:0      [点我收藏+]

Problem:

Sort a linked list using insertion sort.

The node of the linked list is defined as:

1
2
3
4
5
6
7
8
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

 


The insertion sorting is one of the simpleset sorting algorithms, which is of O(n^2) time in the worst case.

The key of the insertion sorting is how to keep track of the "sorted" part and "unsorted" part. For sorting an array we just need to keep track the last index of the sorted part; for sorting a linked list, it becomes much complex since you need maintain two pointers, one points to the last sorted element and the other one points to the first unsorted element. Each time, we insert the first unsorted element into the sorted linked list and update the two pointers.

The C++ code is as follows:

【LeetCode OJ】Insertion Sort List,布布扣,bubuko.com

【LeetCode OJ】Insertion Sort List

原文:http://www.cnblogs.com/zzzdevil/p/3560376.html

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