题解 | 单链表的排序

单链表的排序

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

import java.util.*;


public class Solution {

    public ListNode sortInList (ListNode head) {
        PriorityQueue<ListNode> queue = new PriorityQueue<>(new Comparator<ListNode>() {
            @Override
            public int compare(ListNode node1, ListNode node2) {
                return node1.val - node2.val;
            }
        });
        while (head != null) {
            queue.offer(head);
            head = head.next;
        }

        ListNode start = new ListNode(0);
        ListNode pre = start;
        //OOM
        ListNode tmp = null;
        while (!queue.isEmpty()) {
            tmp = queue.poll();
            //一定要把原先链表断开
            tmp.next = null;
            pre.next = tmp;
            pre = pre.next;
        }
        return start.next;
    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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