队列Queue、优先级队列PriorityQueue和栈Stack

一、队列

(树的层次遍历的时候用到队列:如下)

public void levelOrder(TreeNode subTree) {
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
while (!queue.isEmpty()) {
TreeNode head = queue.remove();
visted(head);
if (head.leftChild != null) {
queue.add(head.leftChild);
}
if (head.rightChild != null) {
queue.add(head.rightChild);
}


}


}

二、优先级队列(相当于小顶堆)

Epeek()
Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
Epoll()
Retrieves and removes the head of this queue, or returns null if this queue is empty.

public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
PriorityQueue priorityQueue = new PriorityQueue();




while (sc.hasNext()) {

System.out.println("请输入整数");
int n = sc.nextInt();
while(priorityQueue.isEmpty()==false){
priorityQueue.remove();
}
System.out.println("请输入数字");
for (int i = 0; i < n; i++) {
int e = sc.nextInt();
priorityQueue.add(e);
}
int ans = 0;
while (priorityQueue.size() > 1) {
int a = (int) priorityQueue.peek();
priorityQueue.remove();
int b = (int) priorityQueue.peek();
priorityQueue.remove();
ans += a + b;
priorityQueue.add(a + b);


}
System.out.println(ans);
}
}

可以改成大顶堆:

import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;


public class test {
private String name;
private int population;
public test(String name, int population)
{
this.name = name;
   this.population = population;
}
public String getName()
{
    return this.name;
}


public int getPopulation()
{
    return this.population;
}
public String toString()
{
    return getName() + " - " + getPopulation();
}
public static void main(String args[])
{
Comparator<test> OrderIsdn =  new Comparator<test>(){
public int compare(test o1, test o2) {
// TODO Auto-generated method stub
int numbera = o1.getPopulation();
int numberb = o2.getPopulation();
if(numberb > numbera)
{
return 1;
}
else if(numberb<numbera)
{
return -1;
}
else
{
return 0;
}

}




};


Queue<test> priorityQueue =  new PriorityQueue<test>(11,OrderIsdn);

/*
PriorityQueue(int initialCapacity,Comparator<? superE> comparator)
          使用指定的初始容量创建一个 PriorityQueue,并根据指定的比较器对元素进行排序。
*/    

test t1 = new test("t1",1);
test t3 = new test("t3",3);
test t2 = new test("t2",2);
test t4 = new test("t4",0);
priorityQueue.add(t1);
priorityQueue.add(t3);
priorityQueue.add(t2);
priorityQueue.add(t4);
System.out.println(priorityQueue.poll().toString());
}
}

三、栈:

Stack stack = new Stack<Integer>();//定义一个保存整型数据的堆栈

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值