初学数据结构:栈和队列

【本节目标】

  • 栈的概念及使用
  • 队列的概念及使用
  • 相关OJ题

1. 栈(Stack)

1.1 概念

栈:一种特殊的线性表,其只允许在固定的一端进行插入和删除元素操作。进行数据插入和删除操作的一端称为栈顶,另一端称为栈底。栈中的数据元素遵守**后进先出LIFO(Last In First Out)**的原则。

  • 压栈:栈的插入操作叫做进栈/压栈/入栈,入数据在栈顶。

  • 出栈:栈的删除操作叫做出栈。出数据在栈顶。

在这里插入图片描述

在这里插入图片描述

1.2 栈的使用

方法功能
Stack()构造一个空的栈
E push(E e)将e入栈,并返回e
E pop()将栈顶元素出栈并返回
E peek()获取栈顶元素
int size()获取栈中有效元素个数
boolean empty()检测栈是否为空
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()); // 获取栈中有效元素个数---> 4
    System.out.println(s.peek()); // 获取栈顶元素---> 4
    s.pop(); // 4出栈,栈中剩余1 2 3,栈顶元素为3
    System.out.println(s.pop()); // 3出栈,栈中剩余1 2 栈顶元素为3
    if(s.empty()){
        System.out.println("栈空");
    }else{
        System.out.println(s.size());
    }
}

1.3 栈的模拟实现

在这里插入图片描述

从上图中可以看到,Stack继承了Vector,Vector和ArrayList类似,都是动态的顺序表,不同的是Vector是线程安全的

public class EmptyStackException extends RuntimeException{
    public EmptyStackException() {

    }

    public EmptyStackException(String message) {
        super(message);
    }
}
import java.util.Arrays;

public class MyStack {
    public int[] elem;
    public int usedSize;

    public static final int DEFAULT_CAPACITY = 10;

    public MyStack() {
        this.elem = new int[DEFAULT_CAPACITY];
    }

    /**
     * 压栈/入栈
     * @param val
     */
    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;
    }

    /**
     * 出栈
     * @return
     */
    public int pop(){
        if (isEmpty()){
            throw new EmptyStackException("栈为空");
        }
        usedSize--;
        return elem[usedSize];
    }
    public boolean isEmpty() {
        return usedSize == 0;
    }
    
    public int peek(){
        if (isEmpty()){
            throw new EmptyStackException("栈为空");
        }
        return elem[usedSize - 1];
    }
}
  • 入栈出栈等操作,时间复杂度均为O(1)

  • 通过链表实现栈,可以使用单链表,也可以使用双链表

  • 不管使用哪种链表,你一定得保证入栈,出栈等操作时间复杂度均为O(1)

    • 使用单向链表来实现栈,入栈采用头插法出栈采用删除头节点的方式
    • 使用双向链表来实现栈,前后都可以实现
    public static void main(String[] args) {
        LinkedList<Integer> stack = new LinkedList<>();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        System.out.println(stack.pop());
        System.out.println(stack.peek());
    }
    

1.4 栈的应用场景

  1. 改变元素的序列

    1. 若进栈序列为 1,2,3,4 ,进栈过程中可以出栈,则下列不可能的一个出栈序列是()
    	A: 1,4,3,2 B: 2,3,4,1 C: 3,1,4,2 D: 3,4,2,1
    
    2.一个栈的初始状态为空。现将元素1、2、3、4、5、A、B、C、D、E依次入栈,然后再依次出栈,则元素出栈的顺序是()
    	A: 12345ABCDE B: EDCBA54321 C: ABCDE12345 D: 54321EDCBA
    	
    参考答案:
    1. C
    2. B
    
  2. 将递归转化为循环

    import java.util.LinkedList;
    import java.util.List;
    import java.util.Stack;
    
    public class PrintReverseOrder {
        static class Node{
            public int val;
            Node next;
    
            public Node(int val) {
                this.val = val;
            }
        }
    
        /**
         * 循环方式逆序打印链表
         * @param head
         */
        public static void PrintList(Node head){
            if (head == null){
                return;
            }
            Stack<Node> s = new Stack<>();
            //将链表中的节点保存在栈中
            Node cur = head;
            while (cur != null){
                s.push(cur);
                cur = cur.next;
            }
    
            //将栈中的元素出栈
            while (!s.empty()){
                System.out.print(s.pop().val + " ");
            }
        }
    
        /**
         * 递归方式逆序打印链表
         * @param head
         */
        public static void PrintList1(Node head) {
            if (head == null) {
                return;
            }
            PrintList1(head.next);
            System.out.print(head.val + " ");
        }
    
    
        public static void main(String[] args) {
            Node head = new Node(1);
            Node A = new Node(2);
            Node B = new Node(3);
            Node C = new Node(4);
            Node D = new Node(5);
    
            head.next = A;
            A.next = B;
            B.next = C;
            C.next = D;
            D.next = null;
    
            PrintList(head);
            System.out.println();
            PrintList1(head);
    
    
        }
    }
    
  3. 有效的括号

    class Solution {
        public boolean isValid(String s) {
            //只要是左括号就入栈,遇到右括号就看是否匹配,不匹配,直接返回false
            //字符串没有遍历完成,但是栈是空的,此时也是不匹配
            //字符串遍历完成,但是栈还是不为空,此时也是不匹配的
            //只要能够找到所有不匹配的情况,剩下的都是匹配的
            Stack<Character> stack = new Stack<>();
    
            //1.遍历字符串
            for(int i = 0; i < s.length(); i++) {
                char ch = s.charAt(i);
                //2.是不是左括号
                if(ch == '(' || ch == '[' || ch == '{'){
                    stack.push(ch);
                }else {
                    //3.右括号
                    //3.1 栈为空
                    if (stack.isEmpty()){
                        return false;
                    }
                    //3.2 栈不为空
                    char ch2 = stack.peek();//左括号
                    if((ch == ')' && ch2 == '(') || (ch == ']' && ch2 == '[') || (ch == '}' && ch2 == '{')){
                        stack.pop();
                    }else {
                        return false;
                    }
    
                }
            }
            //字符串遍历完,考虑栈是否为空
            if(!stack.isEmpty()){
                return false;
            }
            return true;
            
    
        }
    }
    
  4. 逆波兰表达式求值

    class Solution {
        public int evalRPN(String[] tokens) {
            Stack<Integer> stack = new Stack<>();
    
            for(int i = 0; i < tokens.length; i++) {
                String str = tokens[i];
                if(!isOperations(str)) {
                    //不是运算符,说明是数字
                    int val = Integer.valueOf(str);
                    stack.push(val);
    
                }else {
                    //运算符
                    int num2 = stack.pop();
                    int num1 = stack.pop();
                    switch(str) {
                        case "+" :
                            stack.push(num1 + num2);
                            break;
                        case "-" :
                            stack.push(num1 - num2);
                            break;
    
                        case "*" :
                            stack.push(num1 * num2);
                            break;
                        case "/" :
                            stack.push(num1 / num2);
                            break;
                    }
                }
    
            }
    
            return stack.pop();
        }
        //判断当前字符串是不是一个运算符
        private boolean isOperations(String str) {
            if(str.equals("+") || str.equals("-") || str.equals("*") || str.equals("/") ) {
                return true;
            }
            return false;
        }
    }
    
  5. 出栈入栈次序匹配

    import java.util.*;
    
    
    public class Solution {
        /**
         * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
         *
         * 
         * @param pushV int整型一维数组 
         * @param popV int整型一维数组 
         * @return bool布尔型
         */
        public boolean IsPopOrder (int[] pushV, int[] popV) {
            // write code here
            //1.遍历pushV的数组,把pushV数组的元素放到栈当中
            //2.每次放一个元素,就看和popV的元素是否一样
            //3.j++
            //直到遍历完popV
            Stack<Integer> stack = new Stack<>();
            int j = 0;
            for(int i = 0; i < pushV.length; i++){
                stack.push(pushV[i]);
                while (!stack.isEmpty() && j < popV.length && stack.peek() == popV[j] ){
                    stack.pop();
                    j++;
                }
            }
            return j >= popV.length;
            //return stack.isEmpty();
        }
    }
    
  6. 最小栈

    class MinStack {
        //1. 普通栈一定要存储数据
        //2. 最小栈:如果是第一次存放数据,直接放,否则需要和最小栈的栈顶元素比较,小于的时候才能进,等于的时候也要放
        Stack<Integer> stack;
        Stack<Integer> minStack;
        
        public MinStack() {
            stack = new Stack<>();
            minStack = new Stack<>();
        } 
        
        public void push(int val) {
            stack.push(val);
            if(minStack.empty()) {
                minStack.push(val);
            }else {
                int peekNum = minStack.peek();
                if (val <= peekNum) {
                    minStack.push(val);
                }
            }
        }
        
        public void pop() {
            //1.从普通栈pop出去
            //2.最小栈是否pop,判断普通栈pop的数据是否和最小栈的栈顶元素一样,如果一样那么最小栈也要出去
            if(stack.peek().equals(minStack.peek())){
                minStack.pop();
            }
            stack.pop();
        }
        
        public int top() {
            return stack.peek();
        }
        
        public int getMin() {
            return minStack.peek();
        }
    }
    
    /**
     * Your MinStack object will be instantiated and called as such:
     * MinStack obj = new MinStack();
     * obj.push(val);
     * obj.pop();
     * int param_3 = obj.top();
     * int param_4 = obj.getMin();
     */
    

1.5 概念区分

栈、虚拟机栈、栈帧有什么区别呢

  • 栈:数据结构
  • 虚拟机栈:JVM的内存
  • 栈帧:调用方法的时候,开辟的内存

2. 队列(Queue)

2.1 概念

队列:只允许在一端进行插入数据操作在另一端进行删除数据操作的特殊线性表,队列具有先进先出FIFO(First In First Out)

  • 入队列:进行插入操作的一端称为队尾Tail/Rear
  • 出队列:进行删除操作的一端称为队头Head/Front

在这里插入图片描述

2.2 队列的使用

在Java中,Queue是个接口,底层是通过链表实现的

在这里插入图片描述

方法功能
boolean offer(E e)入队列
E poll()出队列
peek()获取队头元素
int size()获取队列中有效元素个数
boolean isEmpty()检测队列是否为空

注意:Queue是个接口,在实例化时必须实例化LinkedList的对象,因为LinkedList实现了Queue接口

public static void main(String[] args) {
    Queue<Integer> q = new LinkedList<>();
    q.offer(1);
    q.offer(2);
    q.offer(3);
    q.offer(4);
    q.offer(5); // 从队尾入队列
    System.out.println(q.size());
    System.out.println(q.peek()); // 获取队头元素
    q.poll();
    System.out.println(q.poll()); // 从队头出队列,并将删除的元素返回
    if(q.isEmpty()){
        System.out.println("队列空");
    }else{
        System.out.println(q.size());
    }
}

2.3 队列模拟实现

队列中既然可以存储元素,那底层肯定要有能够保存元素的空间,通过前面线性表的学习了解到常见的空间类型有两种:顺序结构和链式结构。那么,队列的实现使用顺序结构还是链式结构好?

在这里插入图片描述

public class MyQueue {
    public static class ListNode{
        int val;
        ListNode next;
        ListNode prev;

        public ListNode(int val) {
            this.val = val;
        }
    }

    ListNode first;//队头
    ListNode last;//队尾
    int size = 0;

    /**
     * 入队列
     * 向双向链表位置插入新节点
     * @param e
     */
    public void offer(int e){
        ListNode newNode = new ListNode(e);
        if (first == null){
            first = newNode;
        }else {
            last.next = newNode;
            newNode.prev = last;
        }
        last = newNode;
        size++;
    }

    /**
     * 出队列
     * 将双向链表第一个节点删除掉
     * @return
     */
    public void poll(){

        if (first == null){
            return;
        }
        if (first.next == null){
            first = null;
            last = null;
            return;
        }
        first = first.next;
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return first == null;
    }

    public int peek() {
        if (first == null){
            return -1;
        }
        return first.val;
    }

}

2.4 循环队列

实际中我们有时还会使用一种队列叫循环队列。如操作系统课程讲解生产者消费者模型时可以就会使用循环队列。环形队列通常使用数组实现

在这里插入图片描述

数组下标循环的小技巧

  1. 下标最后再往后(offset 小于 array.length): index = (index + offset) % array.length

    在这里插入图片描述

  2. 下标最前再往前(offset 小于 array.length): index = (index + array.length - offset) % array.length

    在这里插入图片描述

如何区分空与满

  1. 通过添加 usedSize 属性记录

  2. 保留一个位置(浪费空间来表示满)rear = (rear + 1) % len

    public class MyCircularQueue {
        public int[] elem;
        public int front;
        public int rear;
    
        public MyCircularQueue(int k) {
            this.elem = new int[k + 1];
        }
    
        /**
         * 入队
         * @param value
         * @return
         */
        public boolean enQueue(int value){
            if (isFull()){
                return false;
            }
            elem[rear] = value;
            rear = (rear + 1) % elem.length;
            return true;
        }
    
        /**
         * 判断是否队列满了
         * 浪费一个空间
         * rear指向的是无元素
         * @return
         */
        public boolean isFull(){
            return (rear + 1) % elem.length == front;
        }
    
        /**
         * 删除队头操作
         * @return
         */
        public boolean deQueue(){
            if (isEmpty()){
                return false;
            }
            front = (front + 1) % elem.length;
            return true;
         }
    
        /**
         * 判断是否队列为空
         * front和rear相遇的时候为空
         * @return
         */
         public boolean isEmpty(){
            return rear == front;
         }
    
        /**
         * 得到队头元素不删除
         * @return
         */
        public int Front(){
             if (isEmpty()){
                 return -1;
             }
             return elem[front];
         }
    
    
        /**
         * 得到队尾元素不删除
         * @return
         */
        public int Rear(){
            if (isEmpty()){
                return -1;
            }
            int index = (rear == 0) ? elem.length - 1 : rear - 1;
            return elem[index];
    
         }
    
    
    }
    
  3. 使用标记,定义一个boolean flg

在这里插入图片描述

3. 双端队列 (Deque)

双端队列(deque)是指允许两端都可以进行入队和出队操作的队列,deque 是 “double ended queue” 的简称。那就说明元素可以从队头出队和入队也可以从队尾出队和入队

在这里插入图片描述

Deque是一个接口,使用时必须创建LinkedList的对象

在这里插入图片描述

在实际工程中,使用Deque接口是比较多的,栈和队列均可以使用该接口

Deque<Integer> stack = new ArrayDeque<>();//双端队列的线性实现
Deque<Integer> queue = new LinkedList<>();//双端队列的链式实现
  • 双端队列也可以作为栈
  • Stack这个类不是唯一的

4. 面试题

  • 用队列实现栈

    //1.当两个队列都是空的时候,放到第一个队列
    //2.再次“入栈”的时候,放到不为空的队列
    //3.“出栈”的时候,出不为空的队列,出size-1个元素,剩下的元素就是要出栈的元素
    import java.util.LinkedList;
    import java.util.Queue;
    
    public class MyStack {
        private Queue<Integer> qu1;
        private Queue<Integer> qu2;
    
        public MyStack() {
            qu1 = new LinkedList<>();
            qu2 = new LinkedList<>();
        }
    
        /**
         * 入栈
         * @param x
         */
        public void push(int x) {
            if (empty()){
                qu1.offer(x);
                return;
            }
            if (!qu1.isEmpty()){
                qu1.offer(x);
            }else {
                qu2.offer(x);
            }
        }
        /**
         * 出栈
         * @return
         */
        public int pop() {
            if (empty()){
                return -1;
            }
            if (!qu1.isEmpty()){
                int size = qu1.size();;
                for (int i = 0; i < size - 1; i++) {
                    qu2.offer(qu1.poll());
                }
                return qu1.poll();
            }else {
                int size = qu2.size();;
                for (int i = 0; i < size - 1; i++) {
                    qu1.offer(qu2.poll());
                }
                return qu2.poll();
            }
        }
    
        /**
         * 获取栈顶元素
         * @return
         */
        public int top() {
            if (empty()){
                return -1;
            }
            if (!qu1.isEmpty()){
                int size = qu1.size();;
                for (int i = 0; i < size - 1; i++) {
                    qu2.offer(qu1.poll());
                }
                int tmp = qu1.peek();
                qu2.offer(qu1.poll());
                return tmp;
            }else {
                int size = qu2.size();;
                for (int i = 0; i < size - 1; i++) {
                    qu1.offer(qu2.poll());
                }
                int tmp = qu2.peek();
                qu1.offer(qu2.poll());
                return tmp;
            }
        }
    
        /**
         * 判断栈是否为空
         * @return
         */
        public boolean empty() {
            if (qu1.isEmpty() && qu2.isEmpty()){
                return true;
            }
            return false;
        }
    }
    
  • 用栈实现队列

    class MyQueue {
        //"入队":把数据放到第一个栈当中
        //“出队”:出s2这个栈当中的栈顶元素即可,如果s2为空,把s1里面所有的元素全部放到s2中
        //当两个栈都为空,说明模拟的队列为空
    
        private Stack<Integer> s1;
        private Stack<Integer> s2;
        public MyQueue() {
            s1 = new Stack<>();
            s2 = new Stack<>();
        }
    
        public void push(int x) {
            s1.push(x);
        }
    
        public int pop() {
            if (empty()) {
                return -1;
            }
            if (s2.isEmpty()) {
                //弹出s1当中所有的元素放到s2当中
                while (!s1.isEmpty()) {
                    s2.push(s1.pop());
                }
            }
            return s2.pop();
        }
    
        public int peek() {
            if (empty()) {
                return -1;
            }
            if (s2.isEmpty()) {
                //弹出s1当中所有的元素放到s2当中
                while (!s1.isEmpty()) {
                    s2.push(s1.pop());
                }
            }
            return s2.peek();
        }
    
        public boolean empty() {
            return s1.isEmpty() && s2.isEmpty();
        }
    }
    
    /**
     * Your MyQueue object will be instantiated and called as such:
     * MyQueue obj = new MyQueue();
     * obj.push(x);
     * int param_2 = obj.pop();
     * int param_3 = obj.peek();
     * boolean param_4 = obj.empty();
     */
    
  • 14
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

胖了你都蹲不下来撸猫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值