leetcode第4题(sort-list)

题目:

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

思路:
题目要求复杂度为O(nlogn),故可以考虑归并排序的思想。 
归并排序的一般步骤为: 
1)将待排序数组(链表)取中点并一分为二; 
2)递归地对左半部分进行归并排序; 
3)递归地对右半部分进行归并排序; 
4)将两个半部分进行合并(merge),得到结果。
代码:
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode sortList(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        ListNode fast = head.next;
        ListNode slow = head;
        while (fast!=null && fast.next!=null){
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode right = sortList(slow.next);
        slow.next = null;
        ListNode left = sortList(head);
        //合并两个排序好的链表
        ListNode tempHead = new ListNode(0);
        ListNode tempNode = tempHead;
        while (left!=null && right!=null){
            if(left.val<right.val){
                tempNode.next = left;
                left = left.next;
            }
            else{
                tempNode.next = right;
                right = right.next;
            }
            tempNode = tempNode.next;
            if(left != null){
                tempNode.next = left;
            }
            if(right != null){
                tempNode.next = right;
            }
        }
        return tempHead.next;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值