Insertion Sort List
来源:互联网 发布:ubuntu删除谷歌输入法 编辑:程序博客网 时间:2024/05/21 08:58
1.题目
用插入排序对链表排序
Given 1->3->2->0->null
, return 0->1->2->3->null
2.算法
这道题是指定实现插入排序。插入排序是一种O(n^2)复杂度的算法,基本思想就是每次循环找一个元素在当前排好序的结果中的相对位置,然后插入进去
对链表进行插入排序的正确方法是:新建一个头节点,遍历原来的链表,对原链表的每个节点找到新链表中适合插入位置的前指针,然后执行插入操作。
这种操作链表的题有一个技巧就是新建一个dummy作为head,然后把数据插入到dummy的链表中,最后返回dummy.next。
public ListNode insertionSortList(ListNode head) { // write your code here if (head == null) { return null; } ListNode helper = new ListNode(0); ListNode pre = helper; ListNode cur = head; while (cur != null) { ListNode next = cur.next; pre = helper; // 找插入位置 while (pre.next != null && pre.next.val <= cur.val) { pre = pre.next; } //把节点插入对应位置 cur.next = pre.next; pre.next = cur; cur = next; } return helper.next; }
0 0
- Insertion Sort List | leetcode
- Leetcode: Insertion Sort List
- [LeetCode] Insertion Sort List
- Insertion Sort List
- Leetcode: Insertion Sort List
- [LeeCode] Insertion Sort List
- leetcode-Insertion Sort List
- [LeetCode]Insertion Sort List
- Insertion Sort List
- 【LeetCode】Insertion Sort List
- LeetCode | Insertion Sort List
- LeetCode - Insertion Sort List
- Insertion Sort List
- Insertion Sort List
- Insertion Sort List
- Insertion Sort List
- [LeetCode] Insertion Sort List
- list - insertion sort - AC
- Unix 命令之tar
- 调用类实例化为什么添加参数this会错误
- Exporting points in catia into .txt file or to Excel sheet
- 欢迎使用CSDN-markdown编辑器
- Redis服务的集中监控
- Insertion Sort List
- 项目整理(三)——物流
- 缓存、缓存框架、缓存算法讲解
- ios 约束(五)
- java中对象创建、初始化、引用
- deque与vector的主要区别
- 147. Insertion Sort List leetcode list
- Ubuntu 16.04 安装 Tensorflow(GPU支持)
- 页式存储管理(FIFO算法)