栈和队列练习题详解

(1)括号匹配

题目链接:

. - 力扣(LeetCode). - 备战技术面试?力扣提供海量技术面试资源,帮助你高效提升编程技能,轻松拿下世界 IT 名企 Dream Offer。icon-default.png?t=N7T8https://leetcode.cn/problems/valid-parentheses/description/

题目分析:

 

. - 力扣(LeetCode)

 代码实现:

class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        char[] array = s.toCharArray();
        // 遍历数组,将所有左括号放到栈里
        int i = 0;
        for (; i < array.length; i++) {
            if (array[i] == '[' || array[i] == '{' || array[i] == '(') {
                stack.push(array[i]);
            } else {
                if (stack.empty()) {
                    //对应情况
                    //1.第一个元素为左括号
                    //2.左括号少于右括号
                    break;
                } else {
                    char cmp = stack.pop();
                    if (cmp == '(' && array[i] == ')' || cmp == '[' && array[i] == ']'
                            || cmp == '{' && array[i] == '}') {
                        continue;
                    } else {
                        return false;
                    }
                }
            }
        }

        //判断栈和数组是否都遍历完
        if(stack.empty() && i==array.length){
            return true;
        }
        return false;
    }
}

 

(2)逆波兰表达式求值

题目链接:

. - 力扣(LeetCode). - 备战技术面试?力扣提供海量技术面试资源,帮助你高效提升编程技能,轻松拿下世界 IT 名企 Dream Offer。icon-default.png?t=N7T8https://leetcode.cn/problems/evaluate-reverse-polish-notation/description/

题目分析:

 

代码实现:

class Solution {
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack();
        for (int i = 0; i < tokens.length; i++) {
            if (!tokens[i].equals("+") && !tokens[i].equals("-") && !tokens[i].equals("*") && !tokens[i].equals("/")) {
                // 如果是数字,转化为整形放入栈中
                int val = Integer.valueOf(tokens[i]);
                stack.push(val);
            }
            //下面可转化为switch语句
            if (tokens[i].equals("+")) {
                int x = stack.pop();
                int y = stack.pop();
                stack.push(y + x);
            }
            if (tokens[i].equals("-")) {
                int x = stack.pop();
                int y = stack.pop();
                stack.push(y - x);
            }
            if (tokens[i].equals("*")) {
                int x = stack.pop();
                int y = stack.pop();
                stack.push(y * x);
            }
            if (tokens[i].equals("/")) {
                int x = stack.pop();
                int y = stack.pop();
                stack.push(y / x);
            }
        }
        // 此时,栈中剩下的一个元素即为计算的结果
        return stack.pop();
    }
}

 


(3)出栈入栈次序匹配

题目链接:

栈的压入、弹出序列_牛客题霸_牛客网输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假。题目来自【牛客题霸】icon-default.png?t=N7T8https://www.nowcoder.com/practice/d77d11405cc7470d82554cb392585106?tpId=13&&tqId=11174&rp=1&ru=/activity/oj&qru=/ta/coding-interviews/question-ranking

题目分析:

代码实现:

 

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param pushV int整型一维数组
     * @param popV int整型一维数组
     * @return bool布尔型
     */
    public boolean IsPopOrder (int[] pushV, int[] popV) {
        // write code here
        Stack<Integer> stack = new Stack<>();
        int i = 0;
        int j = 0;
        for (; i < pushV.length; i++) {
            //不管pushV[i]和popV[j]是否相等,都要插入栈中
            stack.push(pushV[i]);
            //只要栈不为空就一直于popV元素比较
            while (!stack.empty() && stack.peek()==popV[j]) {
                    stack.pop();
                    j++;
            }
        }

        //全部比较完后如果还有没有出栈的元素则不是弹出顺序
        if(!stack.empty()){
            return false;
        }
        return true;
        
    }
}

(4) 最小栈

题目链接:

. - 力扣(LeetCode). - 备战技术面试?力扣提供海量技术面试资源,帮助你高效提升编程技能,轻松拿下世界 IT 名企 Dream Offer。icon-default.png?t=N7T8https://leetcode.cn/problems/min-stack/

题目分析:

代码实现:

class MinStack {
    Stack<Integer> stack;
    Stack<Integer> minStack;
    public int min;

    public MinStack() {
        stack = new Stack<>();
        minStack = new Stack<>();
    }

    public void push(int val) {
        if (stack.empty()) {
            //如果Stack是空的,则插入的第一个元素视为最小值
            stack.push(val);
            minStack.push(val);
            min = val;
        } else {
            //不是空的,则将插入的值与min进行比较
            if (val < min) {
                min = val;
                stack.push(val);
                minStack.push(val);
            } else {
                stack.push(val);
                minStack.push(min);
            }
        }
    }

    public void pop() {
        stack.pop();
        minStack.pop();
        //pop之后最小值是有可能改变的,因此需要重新确定最小值
        if(!minStack.empty())
        min=minStack.peek();
    }

    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();
 */

 (5)设计循环队列

题目链接:

. - 力扣(LeetCode). - 备战技术面试?力扣提供海量技术面试资源,帮助你高效提升编程技能,轻松拿下世界 IT 名企 Dream Offer。icon-default.png?t=N7T8https://leetcode.cn/problems/design-circular-queue/

题目分析:

  

代码实现:

本题需要注意:一定要创建一个变量记录rear的前一个下标用于返回队尾元素!!!

class MyCircularQueue {
    int rear;
    int front;
    int usedSize;
    int[] array;
    int remember;//记录rear前一个下标,用于返回队尾元素
    public MyCircularQueue(int k) {
        array = new int[k];
    }

    public boolean enQueue(int value) {
        if (isEmpty()) {
            // 数组为空,rear、front都指向数组0下标
            rear = front = 0;
        }
        if (!isFull()) {
            array[rear] = value;
            usedSize++;
            remember=rear;
            rear = (rear + 1) % array.length;
        } else {
            // 数组已满了,无法插入
            return false;
        }
        return true;
    }

    public boolean deQueue() {
        if (isEmpty()) {
            return false;
        }
        // 删除数据直接让front前移一位即可,前面的数据会被覆盖来达到删除的效果
        front = (front + 1) % array.length;
        usedSize--;
        return true;
    }

    public int Front() {
        if (isEmpty()) {
            return -1;
        }
        return array[front];
    }

    public int Rear() {
        if (isEmpty()) {
            return -1;
        }
        return array[remember];
    }

    public boolean isEmpty() {
        return rear == front && usedSize == 0;
    }

    public boolean isFull() {
        return rear == front && usedSize == array.length;
    }
}
/**
 * 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();
 */

 

 (6)用队列实现栈

题目链接:. - 力扣(LeetCode). - 备战技术面试?力扣提供海量技术面试资源,帮助你高效提升编程技能,轻松拿下世界 IT 名企 Dream Offer。icon-default.png?t=N7T8https://leetcode.cn/problems/implement-stack-using-queues/

题目分析:

 

 

代码实现:

class MyStack {
    Queue<Integer> queue1;
    Queue<Integer> queue2;

    public MyStack() {
        queue1=new LinkedList<>();
        queue2=new LinkedList<>();
    }

    public void push(int x) {
          if(empty()){
            //两个队列都为空,把数据放到queue1中
              queue1.offer(x);
          }else if(queue1.isEmpty()){
              queue1.offer(x);
              while(!queue2.isEmpty()){
                  queue1.offer(queue2.poll());
              }
          }else if(queue2.isEmpty()){
              queue2.offer(x);
              while(!queue1.isEmpty()){
                  queue2.offer(queue1.poll());
              }
          }
    }

    public int pop() {
        if(!queue1.isEmpty()){
            return queue1.poll();
        }
        if(!queue2.isEmpty()){
            return queue2.poll();
        }
        return -1;
    }

    public int top() {
       if(!queue1.isEmpty()){
           return queue1.peek();
       }
       if(!queue2.isEmpty()){
           return queue2.peek();
       }
       return -1;
    }

    public boolean empty() {
        if(queue1.isEmpty() && queue2.isEmpty()){
            return true;
        }
        return false;
    }
}

(7)栈实现队列

题目链接:. - 力扣(LeetCode). - 备战技术面试?力扣提供海量技术面试资源,帮助你高效提升编程技能,轻松拿下世界 IT 名企 Dream Offer。icon-default.png?t=N7T8https://leetcode.cn/problems/implement-queue-using-stacks/description/

 

题目分析:

 

 

代码实现:

class MyQueue {
    Stack<Integer> stack1;
    Stack<Integer> stack2;

    public MyQueue() {
        stack1 = new Stack<>();
        stack2 = new Stack<>();
    }

    public void push(int x) {
        if (empty()) {
            stack1.push(x);
        } else {
            if (!stack1.empty()) {
                while (!stack1.empty()) {
                    stack2.push(stack1.pop());
                }
                stack1.push(x);
                while(!stack2.empty()){
                    stack1.push(stack2.pop());
                }
            }
            if (!stack2.empty()) {
                while (!stack2.empty()) {
                    stack1.push(stack2.pop());
                }
                stack2.push(x);
                while(!stack1.empty()){
                    stack2.push(stack1.pop());
                }
            }
        }
    }

    public int pop() {
        if (!stack2.empty()) {
            return stack2.pop();
        }
        if (!stack1.empty()) {
            return stack1.pop();
        }
        return -1;
    }

    public int peek() {
        if (!stack2.empty()) {
            return stack2.peek();
        }
        if (!stack1.empty()) {
            return stack1.peek();
        }
        return -1;
    }

    public boolean empty() {
        if (stack1.empty() && stack2.empty()) {
            return true;
        }
        return false;
    }
}

 

  • 17
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值