题解 | #单链表的排序#7行代码的优先级队列辅助

单链表的排序

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

思路

简单思路,非最优。

  • 链表每个结点值都扔到优先级队列里去。
  • 新建结点的值为pq.poll()

想偷懒不想写排序算法,又不想调Arrays.sort(),才写出了这样的代码,就当练练PriorityQueue,纯属娱乐;-)

实现

import java.util.*;

public class Solution {
    public ListNode sortInList (ListNode head) {
        PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> a - b);
        ListNode cur = head;
        while(cur != null) {
            pq.add(cur.val);
            cur = cur.next;
        }
        ListNode res = new ListNode(-1);
        cur = res;
        while(!pq.isEmpty()) {
            cur.next = new ListNode(pq.poll());
            cur = cur.next;
        }
        return res.next;
    }
}
全部评论

相关推荐

点赞 评论 收藏
分享
一表renzha:手写数字识别就是一个作业而已
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

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