LeetCode:Insertion Sort List (Java)
来源:互联网 发布:淘宝热卖排行榜前十 编辑:程序博客网 时间:2024/06/03 09:15
题目:
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; * next = null; * } * } */public class Solution { public ListNode insertionSortList(ListNode head) { if(null == head || null == head.next) return head; ListNode sortedNode = head; ListNode temp = null; for(ListNode i=head;i!=null;) { if(i.next !=null && i.next.val < sortedNode.val) { if(head.val >= i.next.val) { temp = i.next; i.next = i.next.next; temp.next = head; head = temp; continue; } ListNode cursor = head; while(!(cursor.val <= i.next.val && cursor.next.val >= i.next.val)) cursor = cursor.next; temp = i.next; i.next = i.next.next; temp.next = cursor.next; cursor.next = temp; continue; } i=i.next; sortedNode = i; } return head; }}
0 0
- [Leetcode] Insertion Sort List (Java)
- LeetCode:Insertion Sort List (Java)
- Insertion Sort List Leetcode java
- 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
- hdu 4586——Play the Dice
- FPC的编译宏
- 【Django】创建模板
- poj1609 Tiling Up Blocks
- android界面跳转
- LeetCode:Insertion Sort List (Java)
- 雅思阅读医学类基本常用词汇
- hdu2546 饭卡
- JavaSe基础XX06——面向对象
- 在Linux上安装Hadoop
- 黑马程序员—java高新技术(1)
- 润乾报表使用心得
- SD卡发货单手机卡回到家客户
- boj470-diffsum(桶排)