一、队列
(树的层次遍历的时候用到队列:如下)
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);
}
}
}
二、优先级队列(相当于小顶堆)
E | peek()
Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
|
E | poll()
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>();//定义一个保存整型数据的堆栈