PriorityQueue使用

2023-05-06 16:34:43 浏览数 (1)

C 默认大顶堆,java默认小顶堆

代码语言:javascript复制
import java.util.Comparator;
import java.util.Iterator;
import java.util.PriorityQueue;
import java.util.Queue;

public class PriorityQueueTest
{
	public static class student
	{
		private String name;
		private int stu_num;
		public student(String name, int stu_num)
		{
			this.name = name;
			this.stu_num = stu_num;
		}
		public int getNum()
		{
			return stu_num;
		}
		public String getName()
		{
			return name;
		}
		public String toString()
		{
			return getName()   " "   getNum();
		}
	}
	public static void main(String[] args)
	{
/*PriorityQueue(int initialCapacity, Comparator<? super E> comparator) 
          使用指定的初始容量创建一个 PriorityQueue,并根据指定的比较器对元素进行排序。*/
/*PriorityQueue(int initialCapacity) 
          使用指定的初始容量创建一个 PriorityQueue,并根据其自然顺序对元素进行排序。*/		
		//优先级队列遍历不一定有序,但一个一个出队一定有序
		Comparator<student> order = new Comparator<student>()
				{
					public int compare(student s1, student s2)
					{
						return s1.getNum() - s2.getNum();
					}//这里不像C  有greater和less升序降序直接弄,得自己写
				};//按学号升序排列
		Queue<student> queue = new PriorityQueue<student>(11, order);
		queue.add(new student("lcy", 15170040));
		queue.add(new student("zj", 15170041));
		queue.add(new student("db", 15170039));
		queue.add(new student("xcy", 15170020));
		queue.add(new student("33y", 15170023));
		queue.add(new student("dcy", 15170088));
		queue.add(new student("hy", 15170025));
		queue.add(new student("sf", 15170031));
		while (!queue.isEmpty())
		{
			System.out.println(queue.poll());
		}
		System.out.println("====================");
		Comparator<Integer> order1 = new Comparator<Integer>()
		{
			public int compare(Integer o1, Integer o2)
			{
				return o1 - o2;
			}
		};//小顶堆,若o2-o1就是大顶堆,迭代器不一定有序,但是顺序出队一定有序
		Queue<Integer> q = new PriorityQueue<Integer>(11, order1);
		q.add(2);
		q.add(1);
		q.add(34);
		q.add(6);
		q.add(9);
		q.add(15);
		q.add(9);
		q.add(11);
		q.add(46);
		q.add(5);
		/*int len = q.size();
		for (int i = 0; i < len;   i)
		{
			System.out.print(q.poll()   " ");
		}
		System.out.println(q.toString());*/
		Iterator<Integer> it1 = q.iterator();
		while (it1.hasNext())
		{
			System.out.print(it1.next()   " ");
		}
	}
}

0 人点赞