在OJ上练习编程的时候,有时对栈、队列、堆这些基础数据结构的实现不是考察的重点,而只是要使用这些数据结构解决问题,此时我们熟练掌握语言提供的数据结构API即可。下面对Java中的栈、队列、小根堆和大根堆做一个简单的介绍。
它们都有共用的collections接口中定义的常见函数isEmpty(),可以判断该数据结构中是否还有元素。
栈
Java中有Stack类,但现在已经过时了,不推荐使用。一个更好的方法是使用Deque接口实现栈(Deque意为双端队列,double ended queue)。具体来说又有ArrayDeuqe和LinkedList两种具体类来实现,两者的区别体现在底层分别使用数组和链表来实现。
常用的重要函数包括:
push(); // 向stack栈顶压入一个元素
pop(); // 从stack中弹出栈顶元素
peek(); // 查看stack中栈顶元素,不弹出
// deque接口实现stack
Deque<Integer> stack = new LinkedList<>();
stack.push(1);
stack.push(2);
stack.push(3);
while(!stack.isEmpty()) {
System.out.println(stack.pop());
}
队列
使用Queue接口实现,具体的实现类有LinkedList。
常用的重要函数包括:
向队列尾部添加元素:
offer(); // 如果因为长度不够等原因插入失败,返回false
add(); // 如果插入失败会抛出异常:IllegalStateException;
查看头部元素 ,不改变队列:
peek(); // 如果队列中没有元素,返回null;
element(); // 如果队列中没有元素,则抛出异常:NoSuchElementException;
取出队首元素(返回队首元素,队列中不再包含此元素):
poll(); // 会在没元素时返回null;
remove(); // 会在没元素时抛出异常:NoSuchElementException;
推荐使用offer()、peek()、poll()
// queue接口实现queue
Queue<Integer> queue = new LinkedList<>();
queue.offer(1);
queue.offer(2);
queue.offer(3);
while (!queue.isEmpty()) {
System.out.println(queue.poll());
}
小根堆
PriorityQueue类实现了优先队列,默认是一个小根堆的形式,如果要定义大根堆,需要在初始化的时候加入一个自定义的比较器。
// PriorityQueue 实现heap
// minHeap:PriorityQueue默认实现小根堆
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
minHeap.offer(5);
minHeap.offer(3);
minHeap.offer(4);
minHeap.offer(1);
minHeap.offer(2);
while(!minHeap.isEmpty()) {
System.out.println(minHeap.poll());
}
大根堆
// maxHeap
// 自定义比较器:当compare函数中第一个参数(这里是较大的元素)需要排在前面时,返回一个负数;反之返回一个正数。
class maxComparator implements Comparator<Integer> {
@Override
public int compare(Integer num1, Integer num2) {
return num1 >= num2 ? -1 : 1;
}
}
// 初始化PriorityQueue的时候new一个自定义比较器的对象
PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(new maxComparator());
maxHeap.offer(5);
maxHeap.offer(3);
maxHeap.offer(4);
maxHeap.offer(1);
maxHeap.offer(2);
while(!maxHeap.isEmpty()) {
System.out.println(maxHeap.poll());
}
参考:
https://blog.youkuaiyun.com/huangfan322/article/details/52756441
http://chengfeng96.com/blog/2018/01/20/Java中用Deque接口代替Stack接口完成栈功能/