题解 | #单链表的排序#

单链表的排序

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

import java.util.*;

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

public class Solution {
    /**
     *
     * @param head ListNode类 the head node
     * @return ListNode类
     */
    public ListNode sortInList (ListNode head) {
        // write code here
        //创建集合,将链表所有节点值添加技巧怒
        ArrayList<Integer> list = new ArrayList<>();
        ListNode getNum = head;
        while (getNum != null) {
            list.add(getNum.val);
            getNum = getNum.next;
        }
        //集合值进行排序
        Collections.sort(list);
        int num=list.get(0);
        ListNode tmp=new ListNode(num);
        ListNode returnList=tmp;
        int i=1;
        //将排序好的集合值依次加入链表
        for(Integer integer:list){
            if(i==1){
                i++;
                continue;
            }else{
                ListNode tmpNode=new ListNode(integer);
                tmp.next=tmpNode;
                tmp=tmp.next;
            }

        }
       
        return returnList;
    }
}

全部评论

相关推荐

酷酷的喜马拉雅山:感觉这比一直在初筛不动的好多了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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