利用PriorityQueue,实现多个有序列表合并

master
libospinach 2 years ago
parent 729101d055
commit d38eaca44d

@ -0,0 +1,109 @@
package com.never.basic;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.Comparator;
import java.util.PriorityQueue;
/**
* @Description:
* @author: Bo Li
* @date: 20220830 10:46
*/
public class PriorityQueueDemo {
public static void main(String[] args) {
PriorityQueue<Node> queue = new PriorityQueue<>(new ValComparator());
int[] arr1 = {1,3,5,8};
int[] arr2 = {2,4,5,7};
int[] arr3 = {3,4,9};
Node head1 = array2NodeList(arr1);
Node head2 = array2NodeList(arr2);
Node head3 = array2NodeList(arr3);
queue.add(head1);
queue.add(head2);
queue.add(head3);
Node currentNode = queue.poll();
Node head = currentNode;
if(currentNode.next != null ){
queue.add(currentNode.next);
}
while(!queue.isEmpty()){
Node node = queue.poll();
if(node.next != null){
queue.add(node.next);
}
currentNode.next = node;
currentNode = node;
}
show(head);
}
/**
* @Description:
* @param head
* @return
*/
private static void show(Node head){
while(head.next != null){
System.out.print(head.val+"-->");
head = head.next;
}
}
/**
* @Description:
* @param arr
* @return
*/
private static Node array2NodeList(int[] arr){
Node head = null;
Node currentNode = null;
Node preNode = null;
if(arr.length ==0 || arr == null){
return head;
}
if(arr.length ==1){
head.val = arr[0];
head.next = null;
return head;
}else{
for(int i = arr.length-1 ; i >= 0 ; i--){
if(i == arr.length -1){
currentNode = new Node(arr[i],null);
preNode = currentNode;
}
preNode =currentNode;
currentNode = new Node(arr[i],preNode);
}
head = currentNode;
}
return head;
}
@Data
@AllArgsConstructor
private static class Node{
private int val;
private Node next;
}
/***
* @Description: Node
* @Param:
* @return:
* @Author: libospinach
* @Date: 2022/8/30
*/
private static class ValComparator implements Comparator<Node>{
@Override
public int compare(Node o1, Node o2) {
return o1.val-o2.val;
}
}
}

@ -1,12 +1,13 @@
package com.never.basic;
import java.util.PriorityQueue;
/**
* @Description: TODO
* @author: Bo Li
* @date: 20220829 9:13
*/
public class zeroOneGenerate {
public static void main(String[] args) {
int[] arr = {0,0};
for(int i = 0; i < 100000; i++){

Loading…
Cancel
Save