栈:一种特殊的线性表,其只允许在固定的一端进行插入和删除元素操作。
先进后出

栈的使用

栈的模拟实现

上述的主要代码
java
public class MyStack {
private int[] elem;
private int usedSize;
public MyStack() {
this.elem = new int[5];
}
@Override
public String toString() {
return "MyStack{" +
"elem=" + Arrays.toString(elem) +
", usedSize=" + usedSize +
'}';
}
//压栈
public void push(int val){
if(isFull()){
elem=Arrays.copyOf(elem,2*elem.length);
}
elem[usedSize++]=val;
}
public boolean isFull(){
return this.usedSize==elem.length;
}
//出栈
public int pop(){
if(empty()){
throw new StackEmptyException("栈内元素为空");
}
return elem[--usedSize];
}
public boolean empty(){
return usedSize==0;
}
//获取栈顶元素
public int peek(){
if(empty()){
throw new StackEmptyException("栈内元素为空");
}
return elem[usedSize-1];
}
}
改变元素的序列


将递归转化为循环
比如:逆序打印链表
结果如下




队列:只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性表,队列具有先进先出FIFO(FirstIn First Out) 入队列:进行插入操作的一端称为队尾(Tail/Rear) 出队列:进行删除操作的一端称为队头(Head/Front)
队列的使用
Queue是个接口,在实例化时必须实例化LinkedList的对象,因为LinkedList实现了Queue接口
队列模拟实现(利用双向链表)
先考虑一般情况,再考虑特殊情况

循环队列
环形队列通常使用数组实现
注意事项
代码如下
双端队列 (Deque)
双端队列(deque)是指允许两端都可以进行入队和出队操作的队列,deque 是 "double ended queue" 的简称。那就说明元素可以从队头出队和入队,也可以从队尾出队和入队。
栈和队列均可以使用该接口。
用栈实现队列