147. Insertion Sort List (python)
来源:互联网 发布:gzip linux 编辑:程序博客网 时间:2024/06/08 05:03
Sort a linked list using insertion sort.
题意:采用插入排序法对链表进行排序
思路:类似于扑克牌按照从小到大插入,将第i个元素与左边已排序的元素比较,找到位置插入即可
排序方法可参考:http://blog.csdn.net/yang_yulei/article/details/27237641#comments
数组是将比要插入的元素大的数值往后移,直到遇到比该元素小的值,就把该元素放在比它小的值后面。
Runtime: 346 ms
第一步:为了避免超时,要判断新结点是否有插入左边的必要,通过新结点与左边的邻结点比较,只有在值小于左边的邻结点才插入
第二步:从头结点开始,依次判断新结点插入位置,若新结点值比左边结点大,则p1指针右移。由于第一步比较,所以左边一定能找到比新结点大的结点。
第三步:找到新结点插入的位置,将新结点插入
注意:新结点插入时,需要将新结点赋予给临时结点,然后立即把新结点后面的结点拼接到新结点前一结点后,再将临时结点插入新位置,否则操作顺序一反会导致临时结点操作改变新结点后的结点!!!
p1.next指针指向左边插入的位置,p2.next指向新的结点
# Definition for singly-linked list.# class ListNode(object):# def __init__(self, x):# self.val = x# self.next = Noneclass Solution(object): def insertionSortList(self, head): if not head or not head.next: return head dummy=ListNode(0) dummy.next=head p2=head while p2.next: if p2.val>p2.next.val: p1=dummy while p2.next.val>=p1.next.val: p1=p1.next t=p2.next p2.next=p2.next.next t.next=p1.next p1.next=t else: p2=p2.next return dummy.next
0 0
- 147. Insertion Sort List (python)
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- c/c++ 各个类型所占的字节数
- Java编程中在子类重载方法中调用父类中该方法时,该方法包含递归时出现的调用错误
- Linux系统tput命令用法实例详解
- Codeforces-507B-Amr and Pins
- 深入理解Java的接口和抽象类
- 147. Insertion Sort List (python)
- 迅雷笔试之-纸牌游戏有牛无牛
- 基础总结篇之九:Intent应用详解
- 第一篇博客
- 从一个文件中读取到的内容写到另一个文件中(read,write,open)
- CUDA入门(七)流
- angularjs的过滤器实现搜索与排序
- 设计模式——代理模式(C++)
- 148. Sort List (python)