leetcode:(148) sort list (java)

package Leetcode_LinkedList;

/**
 * 题目:
 *      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
 * 解题思路:
 *      找到链表的middle节点,然后递归对前半部分和后半部分分别进行归并排序,最后对两个以排好序的链表进行Merge
 */
public class SortList_148_1014 {
    public ListNode SortList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }

        ListNode slow = head;
        ListNode fast = head;
        ListNode pre = null;

        //找到链表的中间结点
        while (fast != null && fast.next != null) {
            pre = slow;
            slow = slow.next;
            fast = fast.next.next;
        }

        pre.next = null;

        //对链表的前半部分和后半部分分别进行排序
        ListNode list1 = SortList(head);
        ListNode list2 = SortList(slow);

        return Merge(list1, list2);
    }

    //将两个排序好的链表进行合并
    public ListNode Merge(ListNode list1, ListNode list2) {
        ListNode result = new ListNode(-1);
        ListNode temp = result;

        while (list1 != null && list2 != null) {
            if (list1.val < list2.val) {
                temp.next = list1;
                list1 = list1.next;
            }else {
                temp.next = list2;
                list2 = list2.next;
            }
            temp = temp.next;
        }
        if (list1 != null) {
            temp.next = list1;
        }
        if (list2 != null) {
            temp.next = list2;
        }
        return result.next;
    }

    public static void main(String[] args) {
        ListNode node1 = new ListNode(4);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(1);
        ListNode node4 = new ListNode(3);

        node1.next = node2;
        node2.next = node3;
        node3.next = node4;

        SortList_148_1014 test = new SortList_148_1014();
        ListNode result = test.SortList(node1);

        while (result != null) {
            System.out.print(result.val + " ");
            result = result.next;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值