【数据结构】第五弹——Stack 和 Queue
文章目录
- 一. 栈(Stack)
- 1.1 概念
- 1.2 栈的使用
- 1.3 栈的模拟实现
- 1.3.1 顺序表结构
- 1.3.2 进栈 压栈
- 1.3.3 删除栈顶元素
- 1.3.4 获取栈顶元素
- 1.3.5 自定义异常
- 1.4 栈的应用场景
- 1.改变元素序列
- 2. 将递归转化为循环
- 3. 四道习题
- 1.5 概念分区
- 二. 队列(Queue)
- 2.1 概念
- 2.2 队列的使用
- 2.3 队列模拟实现
- 2.4 循环队列
- 数组下标循环的小技巧
- 设计循环队列
- 三. 双端队列 (Deque)
- 四. 两道面试题
- 4.1 用队列实现栈
- 4.2 用栈实现队列
一. 栈(Stack)
1.1 概念
栈:一种特殊的线性表,其只允许在固定的一端进行插入和删除元素操作。进行数据插入和删除操作的一端称为栈顶,另一端称为栈底。栈中的数据元素遵守后进先出LIFO(Last In First Out)的原则。
压栈:栈的插入操作叫做进栈/压栈/入栈,入数据在栈顶。
出栈:栈的删除操作叫做出栈。出数据在栈顶。
1.2 栈的使用
public static void main(String[] args) {Stack<Integer> s = new Stack();s.push(1);s.push(2);s.push(3);s.push(4);System.out.println(s.size()); // 获取栈中有效元素个数---> 4System.out.println(s.peek()); // 获取栈顶元素---> 4s.pop(); // 4出栈,栈中剩余1 2 3,栈顶元素为3System.out.println(s.pop()); // 3出栈,栈中剩余1 2 栈顶元素为3if(s.empty()){System.out.println("栈空");}else{System.out.println(s.size());}}
1.3 栈的模拟实现
Stack继承了Vector,Vector和ArrayList类似,都是动态的顺序表
1.3.1 顺序表结构
public class MyStack {public int[] elem;public int usedSize;public MyStack() {this.elem = new int[10];}
}
1.3.2 进栈 压栈
public void push(int val) {if(isFull()) {this.elem = Arrays.copyOf(elem,2*elem.length);}elem[usedSize++] = val;}public boolean isFull() {return usedSize == elem.length;}
1.3.3 删除栈顶元素
public int pop() {if(isEmpty()) {throw new EmptyStackException();}int val = elem[usedSize-1];usedSize--;return val;}
1.3.4 获取栈顶元素
public int peek() {if(isEmpty()) {throw new EmptyStackException();}return elem[usedSize-1];}public boolean isEmpty() {return usedSize == 0;}
1.3.5 自定义异常
public class EmptyStackException extends RuntimeException{public EmptyStackException() {}public EmptyStackException(String message) {super(message);}
}
完整代码:
public class MyStack {public int[] elem;public int usedSize;public MyStack() {this.elem = new int[10];}public void push(int val) {if(isFull()) {this.elem = Arrays.copyOf(elem,2*elem.length);}elem[usedSize++] = val;}public boolean isFull() {return usedSize == elem.length;}public int pop() {if(isEmpty()) {throw new EmptyStackException();}int val = elem[usedSize-1];usedSize--;return val;}//获取栈顶元素 但是不删除public int peek() {if(isEmpty()) {throw new EmptyStackException();}return elem[usedSize-1];}public boolean isEmpty() {return usedSize == 0;}
}
1.4 栈的应用场景
1.改变元素序列
2. 将递归转化为循环
逆序打印链表
// 递归方式
void printList(Node head){if(null != head){printList(head.next);System.out.print(head.val + " ");}
}// 循环方式
void printList(Node head){if(null == head){return;}Stack<Node> s = new Stack<>();// 将链表中的结点保存在栈中Node cur = head;while(null != cur){s.push(cur);cur = cur.next;}// 将栈中的元素出栈while(!s.empty()){System.out.print(s.pop().val + " ");}
}
3. 四道习题
都是力扣牛客网上的题目,也是常见的面试题,会在刷题专栏详细讲解
1.5 概念分区
栈 虚拟机栈 栈帧有什么区别?
- 栈是一种通用的数据结构概念,而虚拟机栈是在 Java 虚拟机环境下对栈这种数据结构的具体应用
- 虚拟机栈由多个栈帧组成,每个栈帧对应一个方法的调用。当方法调用开始时,会创建一个新的栈帧并压入虚拟机栈;当方法调用结束时,对应的栈帧会从虚拟机栈中弹出
- 综上所述,栈是一种抽象的数据结构,虚拟机栈是 JVM 中使用栈结构来管理方法调用的具体实现,而栈帧则是虚拟机栈中用于支持单个方法执行的具体数据结构
二. 队列(Queue)
2.1 概念
队列:只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性表,队列具有先进先出FIFO(First In First Out) 入队列:进行插入操作的一端称为队尾(Tail/Rear) 出队列:进行删除操作的一段称为队头(Head/Front)
2.2 队列的使用
在Java中,Queue是个接口,底层是通过链表实现的
每个方法都有一个类似的方法
从效果上没有区别
注意:Queue是个接口,在实例化时必须实例化LinkedList的对象,因为LinkedList实现了Queue接口
LinkedList实现的方法是很多的,可以直接拿来用
那就要这样写了:
LinkedList <Integer> q = new LinkedList<>();
2.3 队列模拟实现
队列中既然可以存储元素,那底层肯定要有能够保存元素的空间,通过前面线性表的学习了解到常见的空间类型有两种:顺序结构 和 链式结构
队列的实现使用顺序结构还是链式结构好?
我们先说链式结构:
双向链表实现队列
static class ListNode{public int val;public ListNode prev;public ListNode next;public ListNode(int val){this.val=val;}}public ListNode first=null;public ListNode last=null;public int useSize=0;public void offer(int val){//addLast尾插ListNode node=new ListNode(val);if(isEmpty()){first=last=null;}last.next=node;node.prev=last;last=last.next;useSize++;}public int poll(){//头删if(isEmpty()){return -1;}int val= first.val;//队头的数据first=first.next;if(first!=null){//只剩一个节点 直接useSize--first.prev=null;}useSize--;return 0;}public int peek(){//获取队头元素if(first==null){return -1;}return first.val;}public boolean isEmpty(){return useSize==0;}
双向链表实现队列效率很高 删除 插入都很方便
如果是数组实现队列该如何实现?
其实按照顺序遍历插入删除 可以实现,但是数组的遍历 一旦往后走就无法回去 被删除的空间没办法再次使用了
如果数组是一个环就好了,这样就可以走回去再次使用空间–这就是循环队列
2.4 循环队列
我们有时还会使用一种队列叫循环队列。如操作系统课程讲解生产者消费者模型时可能就会使用循环队列。环形队列通常使用数组实现。
上面两个一个是空的环形队列 一个是满的环形队列
实现环形队列两个问题:
1.怎么判断空和满?
2.rear 和 front 下标从7到0怎么做到的?
解答:
空:只要front 和 rear 相遇就是空的
满 有三种方法判断
1.定义size size=数组长度就是满
2.添加标记 boolean类型元素 一开始是false一旦开始添加元素就变为true
3.浪费一个空间 判断rear是不是front
先放入元素 再rear++ 判断rear的下一个元素是不是front就可以了
判断 rear=(rear+1)%len
关于这个公式:
数组下标循环的小技巧
利用取模运算得到下标
好了,解决了这两个问题,我们可以使用循环队列了,正好我们来看一道设计循环队列的题目
设计循环队列
设计循环队列
class MyCircularQueue {//数组实现public int front;public int rear;public int[] elem;public MyCircularQueue(int k) {//使用浪费一个空间的方法来判断队列是否满//数组多给一个空间elem=new int[k+1];}public boolean enQueue(int value) {//插入 判满if(isFull()){return false;}elem[rear]=value;rear =(rear+1)%elem.length;return true;}public boolean deQueue() {//删除 判空if(isEmpty()){return false;}//头向后走 因为是环形的所以 向后走也不用担心前面的空间不能使用了front=(front+1)%elem.length;return true;}public int Front() {if(isEmpty()){return -1;}return elem[front];}public int Rear() {if(isEmpty()){return-1;}//return elem[rear];}public boolean isEmpty() {return rear==front;}public boolean isFull() {//rear 的下一个是 frontreturn (rear+1)%elem.length==front;}
}/*** Your MyCircularQueue object will be instantiated and called as such:* MyCircularQueue obj = new MyCircularQueue(k);* boolean param_1 = obj.enQueue(value);* boolean param_2 = obj.deQueue();* int param_3 = obj.Front();* int param_4 = obj.Rear();* boolean param_5 = obj.isEmpty();* boolean param_6 = obj.isFull();*/
如果是这样写示例测到这里会有一个报错
原因在于我们并没有考虑 最重要的一点
rear 从尾到头 怎么办 front删除是向后走了 rear等于0 是可以的
rear 的下一个确实不是front 可以等于0
正确代码如下:
class MyCircularQueue {//数组实现public int front;public int rear;public int[] elem;public MyCircularQueue(int k) {//使用浪费一个空间的方法来判断队列是否满//数组多给一个空间elem=new int[k+1];}public boolean enQueue(int value) {//插入 判满if(isFull()){return false;}elem[rear]=value;rear =(rear+1)%elem.length;return true;}public boolean deQueue() {//删除 判空if(isEmpty()){return false;}//头向后走 因为是环形的所以 向后走也不用担心前面的空间不能使用了front=(front+1)%elem.length;return true;}public int Front() {if(isEmpty()){return -1;}return elem[front];}public int Rear() {if(isEmpty()){return-1;}//int index=(rear==0)?elem.length-1:rear-1;return elem[index];}public boolean isEmpty() {return rear==front;}public boolean isFull() {//rear 的下一个是 frontreturn (rear+1)%elem.length==front;}
}
三. 双端队列 (Deque)
双端队列(deque)是指允许两端都可以进行入队和出队操作的队列,deque 是 “double ended queue” 的简称。那就说明元素可以从队头出队和入队,也可以从队尾出队和入队
Deque是一个接口,使用时必须创建LinkedList的对象
在实际工程中,使用Deque接口是比较多的,栈和队列均可以使用该接口
再来看一下我们数据结构第一篇文章画的图,想打关一样,已经学完这么多了
两种使用方式
Deque<Integer> stack = new ArrayDeque<>();//双端队列的线性实现
Deque<Integer> queue = new LinkedList<>();//双端队列的链式实现
四. 两道面试题
4.1 用队列实现栈
队列实现栈
class MyStack {public Queue<Integer> qu1;public Queue<Integer> qu2;public MyStack() {qu1=new LinkedList<>();qu2=new LinkedList<>();}//入栈public void push(int x) {if(!qu1.isEmpty()){qu1.offer(x);}else if(!qu2.isEmpty()){qu2.offer(x);}else{qu1.offer(x);}}//出栈public int pop() {if(empty()){return-1;}else if(!qu1.isEmpty()){ // 1不是空 将1的size-1个元素放到2for(int i=0;i<qu1.size()-1;i++){qu2.offer(qu1.poll());}return qu1.poll();}else{//2 不为空for(int i=0;i<qu2.size()-1;i++){qu1.offer(qu2.poll());}return qu2.poll();}}public int top() {if(empty()){return-1;}//用一个临时变量 把每个删除的都记录一下,最后一个就是栈顶if(!qu1.isEmpty()){ // 1不是空 将1的size-1个元素放到2int val=0;for(int i=0;i<qu1.size();i++){val=qu1.poll();qu2.offer(val);}return val;}else{//2 不为空int val=0;for(int i=0;i<qu2.size();i++){val=qu2.poll();qu1.offer(val);}return val;}}public boolean empty() {return qu1.isEmpty()&&qu2.isEmpty();}
}
正确代码:
class MyStack {public Queue<Integer> qu1;public Queue<Integer> qu2;public MyStack() {qu1=new LinkedList<>();qu2=new LinkedList<>();}//入栈public void push(int x) {if(!qu1.isEmpty()){qu1.offer(x);}else if(!qu2.isEmpty()){qu2.offer(x);}else{qu1.offer(x);}}//出栈public int pop() {if(empty()){return-1;}else if(!qu1.isEmpty()){ // 1不是空 将1的size-1个元素放到2int size=qu1.size();for(int i=0;i<size-1;i++){qu2.offer(qu1.poll());}return qu1.poll();}else{//2 不为空int size=qu2.size();for(int i=0;i<size-1;i++){qu1.offer(qu2.poll());}return qu2.poll();}}public int top() {if(empty()){return-1;}//用一个临时变量 把每个删除的都记录一下,最后一个就是栈顶if(!qu1.isEmpty()){ // 1不是空 将1的size-1个元素放到2int size=qu1.size();int val=0;for(int i=0;i<size;i++){val=qu1.poll();qu2.offer(val);}return val;}else{//2 不为空int size=qu2.size();int val=0;for(int i=0;i<size;i++){val=qu2.poll();qu1.offer(val);}return val;}}public boolean empty() {return qu1.isEmpty()&&qu2.isEmpty();}
}
4.2 用栈实现队列
按照我们画图得到的思路,写代码:
class MyQueue {
// 两个栈
public ArrayDeque<Integer> s1;
public ArrayDeque<Integer> s2;public MyQueue() {s1=new ArrayDeque<>();s2=new ArrayDeque<>();}public void push(int x) {//入队s1.push(x);}public int pop() {if(empty()){return -1;}if(s2.isEmpty()){while(!s1.isEmpty()){s2.push(s1.pop());}}return s2.pop();}public int peek() {if(empty()){return -1;}if(s2.isEmpty()){while(!s1.isEmpty()){s2.push(s1.pop());}}return s2.peek();}public boolean empty() {return s1.isEmpty()&&s2.isEmpty();}
}