不对具体原理进行介绍,简单记录使用方式。
堆栈
后进先出(LIFO),java中一般使用Stack类。
public class run {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
//入栈,返回该元素
int pushItem = stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4); //stack:4 3 2 1
//判断栈是否为空,空则返回true
if(!stack.isEmpty()){
//出栈,删除并返回栈顶元素;如果堆栈为空,会抛出异常
int popItem = stack.pop(); //popItem:4 stack:3 2 1
}
//查看并返回栈顶元素,但是不删除它
int peekItem = stack.peek(); //peekItem:3 stack:3 2 1
//查看某元素的位序,从栈底开始,即按照入栈顺序,栈底元素为0;没有该元素返回-1
int index = stack.indexOf(0); //index:0
//查看某元素的位序,从栈顶开始,栈顶元素为1;没有该元素返回-1
int index2 = stack.search(0); //index2:3
}
}
队列
先进先出(FIFO),java中一般使用继承了Queue接口的LinkedList类。
public class run {
public static void main(String[] args) {
Queue<Integer> queue = new LinkedList<>();
//入队列,成功返回true,失败返回false
queue.offer(1);
queue.offer(2);
queue.offer(3);
queue.offer(4); //queue:1 2 3 4
//判断队列是否为空,空则返回true
if(!queue.isEmpty()){
//出队列,删除并返回队首元素;如果队列为空,则返回null
int head = queue.poll(); //head:1 queue:2 3 4
}
//查看并返回队首元素,但是不删除它
int headItem = queue.peek(); //headItem:2 queue:2 3 4
}
}