题解 | #单链表的排序#

单链表的排序

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

import java.util.*;

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

public class Solution {
    public ListNode sortInList (ListNode head) {
        //使用数组存储链表元素,然后排序,重新构造链表
        ArrayList<Integer> list = new ArrayList<>();
        ListNode cur = head;
        while (cur != null) {
            list.add(cur.val);
            cur = cur.next;
        }
        //重新构造链表的值
        cur = head;
        //默认为升序排序
        Collections.sort(list);
        //遍历数组构造链表,改变值而已
        for (Integer integer : list) {
            cur.val = integer;
            cur = cur.next;
        }
        return head;
    }
}

#刷题##23届找工作求助阵地#
全部评论

相关推荐

评论
1
收藏
分享

创作者周榜

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