题解

sort-list

http://www.nowcoder.com/questionTerminal/d75c232a0405427098a8d1627930bea6

无非就是归并排序运用在链表上(由于链表不能索引访问,故快排桶排并不合适),拆表用快慢指针即可

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
    public ListNode sortList (ListNode head) {
        // write code here
        if (head == null) {
            return null;
        }
        if (head.next == null) {
            return head;
        }

        ListNode preSlow = head;
        ListNode slow = head;
        ListNode fast = head;
        while (slow != null && fast != null && fast.next != null) {
            preSlow = slow;
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode listA = head;
        ListNode listB = slow;
        preSlow.next = null;
        listA = sortList(listA);
        listB = sortList(listB);
        return merge(listA, listB);
    }

    private ListNode merge (ListNode listA, ListNode listB) {
        ListNode dummy = new ListNode(0);
        ListNode nodeA = listA;
        ListNode nodeB = listB;
        ListNode nodeR = dummy;
        while (nodeA != null && nodeB != null) {
            if (nodeA.val < nodeB.val) {
                nodeR.next = nodeA;
                nodeA = nodeA.next;
            }
            else {
                nodeR.next = nodeB;
                nodeB = nodeB.next;
            }
            nodeR = nodeR.next;
        }
        if (nodeA != null) {
            nodeR.next = nodeA;
        }
        if (nodeB != null) {
            nodeR.next = nodeB;
        }
        return dummy.next;
    }
}
全部评论
归并怎么做到空间常数级呢
2
送花
回复
分享
发布于 2021-09-03 21:58
给唯一的题解点个赞~
点赞
送花
回复
分享
发布于 2020-07-26 13:35
滴滴
校招火热招聘中
官网直投

相关推荐

8 2 评论
分享
牛客网
牛客企业服务