当PriorityQueue存储自定义类(如:链表)或数组时,对PriorityQueue的Comparator()进行重写
1.PriorityQueue()存储自定义类(如:链表)
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public class erchadui {
public static void main(String[] args){
ListNode list1 = new ListNode();//如:1->4->5,
ListNode list2 = new ListNode();//如:2->6,
PriorityQueue<ListNode> que1 = new PriorityQueue<ListNode>(new Comparator<ListNode>() {
@Override
public int compare(ListNode o1, ListNode o2) {
// 按链表头结点的val值进行降序排序
return o1.val - o2.val;
}
});
}
}
2.PriorityQueue()存储Integer数组
public static void main(String[] args){
// int[] nums = new int[]{1,2,3,4,5};
// int[] nums1 = new int[]{8,2,3,4,5};
// int[] nums2 = new int[]{0,2,3,4,5};
Integer[] nums = new Integer[]{1,2,3,4,5};
Integer[] nums1 = new Integer[]{8,2,3,4,5};
Integer[] nums2 = new Integer[]{0,2,3,4,5};
PriorityQueue<Integer[]> que2 = new PriorityQueue<Integer[]>(new Comparator<Integer[]>() {
@Override
public int compare(Integer[] o1, Integer[] o2) {
// 按Integer数组头结点进行降序排序
// 因为自动拆装箱所以可以换成 return o[2]-o[1];
return o2[0].compareTo(o1[0]);
}
});
que2.add(nums);
que2.add(nums1);
que2.add(nums2);
while (que2.size()>0){
Integer[] tmp = que2.poll();
for(int i = 0; i < tmp.length; i++){
System.out.print(tmp[i] + " ");
}
System.out.println();
}
}
可参考:
[1]Java的优先队列PriorityQueue详解