[Data Structure Exercise] Collection of Interview Questions of Stack

Table of contents

Foreword:

1. Multiple-choice questions that can be popped during stacking

2. Turn recursion into loop

3. Reverse Polish expression evaluation

4. Valid Parentheses

5. Stack push and pop sequences

6. Minimal stack 


Foreword:

If you want to learn the data structure well, you need to practice the questions. We not only need to study more questions, but also study them well! For this reason, I started a series of must-do questions. This is the first multiple-choice article. This series will be updated from time to time, so stay tuned!

Detailed Explanation of Stack - WHabcwu's Blog - CSDN Blog


1. Multiple-choice questions that can be popped out of the stack during the stacking process

1. If the push sequence is 1, 2, 3, 4 , and the stack can be popped during the push process, then the following impossible pop sequence is ()
A: 1,4,3,2                 B: 2,3,4,1                 C: 3,1,4,2               D: 3,4,2,1
The sequence of entry and exit of option A:
push(1)->pop() out 1;
 push(2)->push(3)->push(4)->pop() 出4;
pop() out 3;
pop() out 2;
The steps of BCD are the same, and the analysis shows that C is obviously wrong;
Choose C

2. Turn recursion into loop

For example: printing a linked list in reverse order
Use the stack method to solve:
        public void printfList(Node head) {
            if (head == null) {
                return;
            }
            Node cur=head;
            Stack<Node> stack = new Stack<>();
            while (cur!=null){
                stack.push(cur);
                cur=cur.next;
            }
            while(!stack.empty()){
                System.out.println(stack.pop().val);
            }

        }

3. Reverse Polish expression evaluation

Reverse Polish expression evaluation icon-default.png?t=N7T8https://leetcode.cn/problems/evaluate-reverse-polish-notation/

 

In order to thoroughly grasp this question, you must first clearly understand the suffix expression

 Summarize:

(1) Traverse the numbers and push the stack accordingly

(2) Pop 2 numbers when encountering ' + ' ' - ' ' * ' ' / ', the number popped for the first time is used as the right operand, and the number popped for the second time is used as the left operand

(3) Then push the number calculated by (2) onto the stack

(4) Repeat (1) (2) (3)

So the code: 

class Solution {
          public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        for (String x : tokens) {
            if (!isoperation(x)) {
                stack.push(Integer.parseInt(x));
            } else {
                int x1 = stack.pop();
                int x2 = stack.pop();
                switch (x) {
                    case "+":
                        stack.push(x2 + x1);
                        break;
                    case "-":
                        stack.push(x2 - x1);
                        break;
                    case "*":
                        stack.push(x2 * x1);
                        break;
                    case "/":
                        stack.push(x2 / x1);
                        break;
                }
            }
        }
        return stack.pop();
    }

    public boolean isoperation(String x) {
        if (x.equals("+")  || x.equals("-") || x.equals("*") || x.equals("/")) {
            return true;
        }
        return false;
    }
}

4. Valid Parentheses

Valid Parentheses icon-default.png?t=N7T8https://leetcode.cn/problems/valid-parentheses/

 

class Solution {
    public boolean isValid(String s) {
     Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char x=s.charAt(i);
            if(x=='('||x=='{'||x=='['){
                stack.push(x);
            }else{
                if(stack.empty()){
                    return false;
                }
                char y=stack.peek();
                if(y=='('&&x==')'||y=='{'&&x=='}'||y=='['&&x==']'){
                    stack.pop();
                }else{
                    return false;
                }
            }
        }
        if(!stack.empty()){
            return false;
        }
        return true;
    }
    
}

 Parse:

(1) Traverse the given string, since the left parenthesis encountered later must be closed first , so we can put this left parenthesis on the top of the stack.

(2) When we encounter a right parenthesis, we can take out the left parenthesis on the top of the stack and judge whether they are the same type of parentheses. If the stack is empty, return flase, if it is not empty but not the same type, it also returns false.

(3) After the traversal, if there is no left parenthesis in the stack, return false.


5. Stack push and pop sequences

 

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pushV int整型一维数组 
     * @param popV int整型一维数组 
     * @return bool布尔型
     */
      public boolean IsPopOrder (int[] pushV, int[] popV) {
        Stack<Integer> stack = new Stack<>();
        int j=0;
        for (int i = 0; i < pushV.length; i++) {
            stack.push(pushV[i]);
            while(j<popV.length&&!stack.empty()&&stack.peek().equals(popV[j])){
                stack.pop();
                j++;
            }
        }
        return stack.empty();
    }
}

Parse:


6. Minimal stack 

 Minimum stack icon-default.png?t=N7T8https://leetcode.cn/problems/min-stack/

 

import java.util.Stack;

public class MinStack {
    private Stack<Integer> stack;
    private Stack<Integer> minstack;

    public MinStack() {
        this.stack = new Stack<>();
        this.minstack = new Stack<>();
    }

    public void push(int val) {
        stack.push(val);
        if (minstack.empty()) {
            minstack.push(val);
        } else {
            if (minstack.peek() >= val) {
                minstack.push(val);
            }
        }
    }

    public void pop() {
           if(!stack.empty()){
            int x = stack.pop();
            if (x == minstack.peek()) {
                minstack.pop();
            }
        }
    }

    public int top() {
        return stack.peek();
    }

    public int getMin() {
        return minstack.peek();
    }
}

 Parse:

Auxiliary stack method:

(1) One is used to store data normally -> stack

(1) One is used to store the minimum data->minstack

  private Stack<Integer> stack;
    private Stack<Integer> minstack;

 push:

The stack is pushed into the stack without distinction, and minstack is judged. If it is empty, it is directly pushed into the stack. If it is not empty, it needs to be compared with the top element of the stack. If it is less than or equal to, it is pushed into the stack.

The rest are too simple to describe.


The above is my personal sharing, if you have any questions, welcome to discuss! !

I've seen this, why don't you pay attention and give a free like 

 

Guess you like

Origin blog.csdn.net/WHabc2002/article/details/132678020