题解 | #单链表的排序#

单链表的排序

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类
     */
    public ListNode sortInList (ListNode head) {
        //step1:基本判空处理
        if(head == null || head.next == null){
            return head;
        }
        //step2:使用快慢指针,查询当前本次归并处理的中点
        ListNode fast = head.next;
        ListNode slow = head;
        while(fast != null && fast.next != null){ //保证快指针不会异常
            slow = slow.next;
            fast = fast.next.next;
        }
        //step3:找到本轮中点节点,进行两链表的拆分
        ListNode temp = slow.next;
        slow.next = null;  //断开链表
        //step4:归并继续拆分、合并
        return mergeList(sortInList(head),sortInList(temp));
    }


    public ListNode mergeList(ListNode head1,ListNode head2){
        //基本判空
        if(head1 == null){return head2;}
        if(head2 == null){return head1;}

        //构造双指针
        ListNode head1Cursor = head1;
        ListNode head2Cursor = head2;

        //构造新的头节点,移动双指针
        ListNode newHead = new ListNode(0);
        ListNode newCursor = newHead; 
        while(head1Cursor!=null && head2Cursor!=null){
            if(head1Cursor.val<head2Cursor.val){
                newCursor.next = head1Cursor;
                head1Cursor = head1Cursor.next;
            }else {
                newCursor.next = head2Cursor;
                head2Cursor = head2Cursor.next;
            }
            //移动newCursor
            newCursor = newCursor.next;
        }
        //head1Cursor和head2Cursor存在提前终止的情况,需连接其后半部分
        newCursor.next = head1Cursor == null ? head2Cursor : head1Cursor;

        return newHead.next;
    }
}

全部评论

相关推荐

2025年10月3日中午,在写完定时一年后发给自己的信之后,敲下键盘,写下这篇文字。我把标题的“所有人”加了引号,因为如我们所见,确实有的人顺风顺水,每天过的很开心,或是早早进入大厂,或是年纪轻轻就拿到了高薪offer,或是过着可能我努力十年也不一定实现的生活。但也许,不是每个人的痛苦都能被别人看到的,这个月我经常会哭,被骗6000块钱、手上钱不够导致拖欠房租、生活还要借朋友钱、国庆长假也没有钱去旅游,互联网公司不稳定担心试用期不过(毕竟上段实习就是被裁了,一有点风吹草动就害怕),但这样的我,不是所有人都知道的,居然是有些朋友的羡慕对象。回忆我的七年“长跑”别人都是多年幸福的恋爱长跑,我没有恋...
故事和酒66:让每一颗种子找到合适自己的生长方式,最终绽放出独一无二的花朵,这远比所有人都被迫长成同一棵“参天大树”的世界,更加美好和富有生机。这是社会和环境的问题,而不是我们的问题。然而就是在这样的环境中,楼主依然能突破自我,逆势成长,其中的艰辛可想而知。这一路的苦难终究会化作你成长的养料
你小时候最想从事什么职业
点赞 评论 收藏
分享
面试拷打成m:我感觉他说的挺对的,感觉我找不到工作也要去送外卖了,至少饿不死
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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