148. Sort List 给链表排序

题目描述:

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

Example 1:

Input: 4->2->1->3
Output: 1->2->3->4

Example 2:

Input: -1->5->3->4->0
Output: -1->0->3->4->5

思路:

让有序的链表作为另外一个链表,让给原来链表中的每个指针加入到新的有序链表中

tips:

为了让插入的时候方便,新链表设置了一个头结点,头结点赋予最小的值(Integer.MIN_VALUE),最后再删去头结点。

 

代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode sortList(ListNode head) {
        if(head ==null ||head.next == null) return head;

        //给list设置成为带头结点的
        ListNode list = new ListNode(Integer.MIN_VALUE);
        list.next=null;

        while(head != null){
            ListNode bei = head;
            head = head.next;
            //找到要插入的位置
            ListNode t = list;
            while (t.next != null){
                if(t.val < bei.val){
                    if(t.next.val >= bei.val){
                        //查在t后面
                        break;
                    }
                    t = t.next;
                }
            }
            bei.next = t.next;
            t.next = bei;

        }
        list = list.next;
        return list;
    }
}

148. Sort List 给链表排序_第1张图片

结果显示:时间太慢了,怎么提高效率呢?

思考:因为我的空间复杂度比较低,所以考虑空间换时间

怎么做呢?

有待研究。。。。

归并:

public ListNode sortList(ListNode head) {
    if(head == null || head.next == null){
        return head;
    }
    ListNode newHead = new ListNode(0);
    newHead.next = head;

    ListNode slow = newHead, quick = newHead;

    while(quick != null && quick.next != null){
        slow = slow.next;
        quick = quick.next.next;
    }
    if(quick != null){
        slow = slow.next;
    }

    newHead = head;
    while(head != null && head.next != slow){
        head = head.next;
    }
    if(head != null)
        head.next = null;

    return merge(sortList(newHead),sortList(slow));
}
private ListNode merge(ListNode head1, ListNode head2){
    ListNode newHead = new ListNode(0);
    ListNode resHead = newHead;
    while(head1 != null && head2 != null){
        if(head1.val < head2.val){
            newHead.next = head1;
            head1 = head1.next;
        }else{
            newHead.next = head2;
            head2 = head2.next;
        }
        newHead = newHead.next;
    }
    if(head1 != null){
        newHead.next = head1;
    }
    if(head2 != null){
        newHead.next = head2;
    }
    return resHead.next;
}

 

你可能感兴趣的:(leetcode,java面试,数据结构)