题解 | 单链表的排序

单链表的排序

https://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 the head node
     * @return ListNode类
     */
    // 对一个无序单链表,对其按升序排序
    // 空间复杂度O(n),时间复杂度O(nlogn);应该使用归并排序
    public ListNode sortInList (ListNode head) {
        if(head == null || head.next == null) return head;
        // write code here
        ListNode left = head;
        ListNode mid = head.next;
        ListNode right = head.next.next;
        // 右边的指针到达末尾时,中间的指针指向该段链表的中间
        while(right != null && right.next != null){
            left = left.next;
            mid = mid.next;
            right = right.next.next;
        }
        // 左边指针指向左段的左右一个节点,从这里断开
        left.next = null;
        return merge(sortInList(head),sortInList(mid));

    }

    public ListNode merge(ListNode pHead1, ListNode pHead2){
        if(pHead1 == null)
            return pHead2;
        if(pHead2 == null)
            return pHead1;
        ListNode head = new ListNode(0);
        ListNode cur = head;
        while(pHead1 != null && pHead2 != null){
            if(pHead1.val <= pHead2.val){
                cur.next = pHead1;
                pHead1 = pHead1.next;
            }else{
                cur.next = pHead2;
                pHead2 = pHead2.next;
            }
            cur = cur.next;
        }
        if(pHead1 != null)
            cur.next = pHead1;
        else
            cur.next = pHead2;
        return head.next;
    }
}

全部评论

相关推荐

07-15 00:33
江苏大学 Java
代码飞升:哈哈哈哈评论区三个打广告的
简历中的项目经历要怎么写
点赞 评论 收藏
分享
07-25 10:31
门头沟学院 Java
求问各位大佬,笔试都考点啥
投递科大讯飞等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务