1. PriorityQueue
优先队列是由PriorityQueue
实现的。其中的类必须实现compareTo
方法。
推荐博客https://www.cnblogs.com/Elliott-Su-Faith-change-our-life/p/7472265.html
方法:
1. 添加
add(object); //插入失败时抛出异常
offer(object); //插入失败时返回false
2. 获取
element() //获取失败时抛出异常
peek() //获取失败时返回false
3. 删除
remove() //删除失败抛出异常
poll() //删除失败返回false
remove(object)
contain(object)
Java优先队列默认是小根堆,对于类的优先队列,需要用接口Comparable重载其中的compareTo()函数,自行规定比较方法,可以故意与原比较大小相反,将小根堆变为大根堆。
/**
*ProrityQueue
*@author Hongchuan CAO
*/
package ACM;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Scanner;
public class Main {
public static void main(String arg[]){
Node[] node = new Node[10];
for(int i=0;i<10;i++){
node[i] = new Node();
node[i].a = 100-i;
}
Arrays.sort(node);
for(Node xx : node){
System.out.print(xx.a+" ");
}
}
}
class Node implements Comparable{
public int a;
@Override
public int compareTo(Object obj){
Node other = (Node) obj;
if(this.a<other.a) return -1;
else if(this.a>other.a) return 1;
return 0;
}
}
其中compareTo()默认比较方法,
Queue
Queue 是一个接口,其具体是由LinkedList
实现实现的。
常用方法
Queue<String> queue = new LinkedList<String>();
//成功返回true,失败返回false或null
//添加到队尾
queue.offer(E x);
//获得并移除队首元素
queue.poll();
//获得队首元素但不删除
queue.peek();
// LinkedList
//添加
offerFirst(E e);
offerLast(E e);
//获取 (如果为空,返回NULL)
peekFirst();
peekLast();
//删除 (如果为空,返回NULL)
pollFirst();
pollLast();
Deque
Java 中没有双向队列的接口,可以直接使用LinkedList
实现。
LinkedList<String> deque = new LinkedList<String>();
//加入元素
deque.addFirst();
deque.addLast();
deque.offerFirst();
deque.offerLast();
//获得元素
deque.getFisrt();
deque.getLast();
deque.peekFirst();
deque.peekLast();
//删除元素
deque.removeFirst();
deque.removeLast();
deque.pollFirst();
deque.pollLast();
Stack
Stack
继承自Vector
Stack<String> stack = new Stack<String>();
//栈顶加入元素
stack.push(E x);
//栈顶获得元素
stack.peek();
//栈顶删除元素
stack.pop();
stack.empty();
stack.search(Object o);
也可以直接利用LinkedList
实现栈的功能
LinkedList<String> stack = new LinkedList<String>();
stack.offerFirst();
stack.peekFirst();
stack.pollFirst();