题解 | #单链表的排序#

单链表的排序

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) {
        // 思路1:构建辅助数组
        if(head==null) {
            return head;
        }
        List<Integer> temp = new ArrayList<>();
        while(head!=null) {
            temp.add(head.val);
            head = head.next;
        }
        Collections.sort(temp);
        ListNode result = new ListNode(-1);
        ListNode tempList = result;
        for(int i=0;i<temp.size();i++) {
            ListNode tempNode = new ListNode(temp.get(i));
            tempList.next = tempNode;
            tempList = tempList.next;
        }
        return result.next;
    }
}

辅助数组法:本题的关键在于理解链表的结构,注意 tempList.next = tempNode; tempList = tempList.next;

全部评论

相关推荐

认真搞学习:28小登的建议,投算法岗不要写什么物理竞赛,互联网+,多写点项目,用什么算法做了什么。还有本科算法是不可能的开发你这个也没有项目啊
点赞 评论 收藏
分享
仁者伍敌:牛子这些人还会点一个自动回复,boss都不带回复的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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