LeetCode 147. Insertion Sort List

原题链接在这里:https://leetcode.com/problems/insertion-sort-list/

题目:

Sort a linked list using insertion sort.

题解:

Sort List类似. 

当出现cur.val > cur.next.val时就需要insert cur.next到对应位置.

Time Complexity: O(n^2). Space: O(1).

AC Java:

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 class Solution {
10     public ListNode insertionSortList(ListNode head) {
11         if(head == null || head.next == null){
12             return head;
13         }
14         
15         ListNode dummy = new ListNode(0);
16         dummy.next = head;
17         
18         while(head.next != null){
19             if(head.val > head.next.val){ //当出现前一个点val 比后一个点val大时,就要找到添加位置
20                 ListNode mark = dummy;
21                 while(mark.next != null && mark.next.val<head.next.val){ //找mark位置
22                     mark = mark.next;
23                 }
24                 
25                 ListNode temp = head.next;
26                 head.next = head.next.next;
27                 temp.next = mark.next;
28                 mark.next = temp;
29             }else{
30                 head = head.next;
31             }
32         }
33         
34         return dummy.next;
35     }
36 }

 

posted @ 2015-09-03 01:16  Dylan_Java_NYC  阅读(212)  评论(0编辑  收藏  举报