LeetCode:Insertion Sort List (Java)
2014-08-08 01:07
387 查看
题目:
思路:
算法导论讲的插入排序方法当一个数插入已排序数里面的时候是从后往前比较,知道找到合适位置。但是单链表是无法从后往前比较的。但是插入排序既可以从后往前比较,也可以从前往后比较。明白这点,对单链表插入排序应该就没什么难度了。
代码:
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; } }
相关文章推荐
- LeetCode147_Insertion Sort List(用插入排序算法对链表进行排序) Java题解
- Java for LeetCode 147 Insertion Sort List
- Insertion Sort List Leetcode java
- [Leetcode][JAVA] Insertion Sort List
- [Leetcode] Insertion Sort List (Java)
- leetcode 147 Insertion Sort List java 算法
- Insertion Sort List Leetcode java
- LeetCode 147 — Insertion Sort List(C++ Java Python)
- 【LeetCode-面试算法经典-Java实现】【147-Insertion Sort List(链表插入排序)】
- Leetcode Insertion Sort List 解题报告
- LeetCode----Insertion sort list
- 【LeetCode】Insertion Sort List
- LeetCode - Insertion Sort List
- LeetCode - Insertion Sort List
- [Leetcode] Sort List (Java)
- LeetCode-Insertion Sort List
- [leetcode]Insertion Sort List
- Leetcode: Insertion Sort List
- LeetCode(147) Insertion Sort List
- [LeetCode]Insertion Sort List