147. Insertion Sort List

题目:

Sort a linked list in O(n log n) time using constant space complexity. 

Hide Tags
  Linked List Sort  

链接: http://leetcode.com/problems/sort-list/

题解:

链表插入排序,考察基本功。worst case时间复杂度是O(n2) , best case时间复杂度是O(n)。   好久没做题最近完全懈怠了,要继续努力啊。

Time Complexity - O(n2) (worst case), Space Complexity - O(n)。

public class Solution {

    public ListNode insertionSortList(ListNode head) {

        if(head == null || head.next == null)

            return head;

        ListNode dummy = new ListNode(-1);

        

        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;

    }

}

 

测试:

你可能感兴趣的:(insert)