题解 | #链表排序#

链表排序

http://www.nowcoder.com/practice/d75c232a0405427098a8d1627930bea6

取巧的方法。实际上对链表中val值进行排序然后重新赋值一次。严格来讲没有操作链表指针,没啥技术含量。

import java.util.*;

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

public class Solution {
    /**
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
    public ListNode sortList (ListNode head) {
        // write code here
        if(head == null || head.next == null) return head;
        ListNode cur = head;
        ArrayList<Integer> list = new ArrayList<>();
        while(cur!= null){
            list.add(cur.val);
            cur = cur.next;
        }
        Collections.sort(list);
        cur = head;
        int i = 0;
        while(cur != null){
            cur.val = list.get(i);
            cur = cur.next;
            i++;
        }
        return head;
    }
}
全部评论
要求空间复杂度是常数级,你这就是O(n)了啊
点赞 回复 分享
发布于 2021-09-11 10:16

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务