[LintCode] Insertion Sort List
Posted Push your limit!
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LintCode] Insertion Sort List相关的知识,希望对你有一定的参考价值。
Sort a linked list using insertion sort.
Example
Given 1->3->2->0->null
, return 0->1->2->3->null
.
1 /** 2 * Definition for ListNode. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int val) { 7 * this.val = val; 8 * this.next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 /** 14 * @param head: The first node of linked list. 15 * @return: The head of linked list. 16 */ 17 public ListNode insertionSortList(ListNode head) { 18 if(head == null || head.next == null){ 19 return head; 20 } 21 ListNode dummy = new ListNode(0); 22 dummy.next = head; 23 ListNode sorted = dummy.next; ListNode prev = dummy; 24 ListNode unsorted = head.next; 25 sorted.next = null; 26 while(unsorted != null){ 27 while(sorted != null && sorted.val <= unsorted.val){ 28 prev = sorted; 29 sorted = sorted.next; 30 } 31 ListNode temp = unsorted.next; 32 unsorted.next = sorted; 33 prev.next = unsorted; 34 35 unsorted = temp; 36 37 prev = dummy; 38 sorted = dummy.next; 39 } 40 return dummy.next; 41 } 42 }
以上是关于[LintCode] Insertion Sort List的主要内容,如果未能解决你的问题,请参考以下文章
#Leetcode# 147. Insertion Sort List