LeetCode 147. Insertion Sort List(插入有序链表)
来源:互联网 发布:linux命令删除文件内容 编辑:程序博客网 时间:2024/05/24 04:16
原题网址:https://leetcode.com/problems/insertion-sort-list/
Sort a linked list using insertion sort.
方法:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode insertionSortList(ListNode head) { if (head == null || head.next == null) { return head; } ListNode current = head.next; head.next = null; while (current != null) { ListNode next = current.next; if (current.val <= head.val) { current.next = head; head = current; } else { ListNode insert = head; while (insert.next != null && current.val > insert.next.val) { insert = insert.next; } if (insert.next == null) { current.next = null; insert.next = current; } else { current.next = insert.next; insert.next = current; } } current = next; } return head; }}
优化:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution {public ListNode insertionSortList(ListNode head) { /* 下面这个是网上找来的 */ ListNode dummy = new ListNode(0); // 这个dummy的作用是,把head开头的链表一个个的插入到dummy开头的链表里 // 所以这里不需要dummy.next = head; while (head != null) { ListNode node = dummy; while (node.next != null && node.next.val < head.val) { node = node.next; } ListNode temp = head.next; head.next = node.next; node.next = head; head = temp; } return dummy.next; }}
0 0
- LeetCode 147. Insertion Sort List(插入有序链表)
- leetcode 147. Insertion Sort List-链表插入排序
- LeetCode-147. Insertion Sort List (JAVA)链表插入排序
- leetcode 147. Insertion Sort List 链表插入排序
- LeetCode | Insertion Sort List(插入法排序链表)
- LeetCode 147 Insertion Sort List(链表插入排序)
- Leetcode刷题记——147. Insertion Sort List(插入排序链表)
- 147. Insertion Sort List(链表的插入排序)
- Insertion Sort List 链表插入排序@LeetCode
- LeetCode:Insertion Sort List//链表插入排序
- leetcode Insertion Sort List(链表插入排序)
- [C++]LeetCode: 126 Insertion Sort List (插入排序链表)
- Leetcode Insertion Sort List 插入排序链表
- LeetCode Insertion Sort List 链表的插入排序
- [LeetCode] Insertion Sort List 单向链表插入排序
- LeetCode 147. Insertion Sort List插入排序链表的高效简单解法
- 147. Insertion Sort List(插入排序)
- leetcode——Insertion Sort List 对链表进行插入排序(AC)
- Cisco路由器进行ip限速的配置方法
- 详谈 UNIX 环境进程异常退出
- CentOS 6.3开机自动挂载磁盘和文件夹
- 内核线程、轻量级进程、用户线程三种线程概念解惑(线程≠轻量级进程)
- 苹果App Store新规:6月1日后所有应用必须支持IPv6-only网络
- LeetCode 147. Insertion Sort List(插入有序链表)
- Linux里必须会的redis命令
- 2016.5.23笔记
- Android DEX 分包
- eclipse使用
- Android面试题
- Java导出jar包(并用bat命令执行)
- iOS、mac开源项目及库汇总
- ArrayList源码分析(JDK1.8)