LeetCode Insertion Sort List
来源:互联网 发布:无法打开awrrpt.sql 编辑:程序博客网 时间:2024/05/16 12:26
LeetCode解题之Insertion Sort List
原题
通过插入排序的方法排序一个链表。
注意点:
- 无
例子:
无
解题思路
数组的插入排序很简单,将元素依次放入已经排好序的数组中的正确位置。链表与数组的操作稍微有些不同,数组是将比要插入的元素大的数值往后移,直到遇到比该元素小的值,就把该元素放在比它小的值后面。但单链表只能从头开始判断新的节点该插入到哪里。链表也可以根据尾节点进行优化,如果要插入的节点比尾节点还大的话,就不用从头开始找插入的位置了。插入时要注意链表插入操作,Python写链表相关操作还是很方便的。
AC源码
# Definition for singly-linked list.class ListNode(object): def __init__(self, x): self.val = x self.next = Noneclass Solution(object): def insertionSortList(self, head): """ :type head: ListNode :rtype: ListNode """ dummy = ListNode(-1) cur = dummy while head: # check if it is needed to reset the cur pointer if cur and cur.val > head.val: cur = dummy # find the place to insert while cur.next and cur.next.val < head.val: cur = cur.next # insert and sort the next element cur.next, cur.next.next, head = head, cur.next, head.next return dummy.nextif __name__ == "__main__": None
欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。
0 0
- Insertion Sort List | leetcode
- Leetcode: Insertion Sort List
- [LeetCode] Insertion Sort List
- Leetcode: Insertion Sort List
- leetcode-Insertion Sort List
- [LeetCode]Insertion Sort List
- 【LeetCode】Insertion Sort List
- LeetCode | Insertion Sort List
- LeetCode - Insertion Sort List
- [LeetCode] Insertion Sort List
- Insertion Sort List (LeetCode)
- [LeetCode] Insertion Sort List
- [LeetCode]Insertion Sort List
- leetcode Insertion Sort List
- Insertion Sort List -- LeetCode
- Insertion Sort List (LeetCode)
- LeetCode Insertion Sort List
- leetcode Insertion Sort List
- 如何把文件中的数据读入程序
- 黑马程序员——java基础---按位& |、常量、变量
- 团体程序设计天梯赛
- ffmpeg编译的个人配置
- 文章标题
- LeetCode Insertion Sort List
- Java的基本点
- 对递归的理解
- 虚基类
- ubuntu安装使用锐捷认证上网
- 5.18
- C++实践参考——分数类中的运算符重载
- C++第6次作业
- 欢迎使用CSDN-markdown编辑器