Data structure java version stack

content 

First, the basic concept distinction of stack

2. Common operations of stack and examination of common question types

First, the basic concept distinction of stack

What is a stack?

The stack is actually a data structure, characterized by last-in, first-out

What is the Java Virtual Stack?

 At this point, the Java virtual machine stack is just a piece of memory in the JVM, which is generally used to store, for example: local variables

What is a stack frame?

When calling a function, we will open up a piece of memory in the JVM virtual machine stack for this function called a stack frame

2. Common operations of stack and examination of common question types

1. Common operations of stack

method explain
E push(E item) push onto the stack
E pop() pop
E peek() View the top element of the stack
boolean empty() Check if the stack is empty

1. Test common operations:

import java.util.*;

public class TestDemo {
    public static void main(String[] args) {
        Stack<Integer> stack=new Stack<>();
        //入栈
        stack.push(1);
        stack.push(2);
        System.out.println(stack);
        //查看栈顶元素
        System.out.println(stack.peek());
        System.out.println(stack);
        //出栈
        System.out.println(stack.pop());
        System.out.println(stack);
        System.out.println(stack.isEmpty());
    }

}

Note: The operation of stack.pop() is to pop the top element of the stack, after which the top element of the stack will no longer exist 

           The operation of stack.peek() is to view the top element of the stack, after which the top element of the stack still exists 

 2. Do-it-yourself implementation stack 

Judging from the source code, the bottom layer of the stack is an array:

import java.util.*;

//自己实现栈
public class MyStack {
public int[] elem;
//判断放入的个数,即容量的大小
public int usedSize;
public MyStack(){
    this.elem=new int[5];
}
//关于入栈
public void push(int val){
    //第一步,判断是否满栈
    if(isFull()){
        //扩容
        Arrays.copyOf(this.elem,2*this.elem.length);
    }
    this.elem[this.usedSize]=val;
    this.usedSize++;
}
public boolean isFull(){
    return this.usedSize==this.elem.length;
}
//出栈
public int pop(){
    if(isEmpty()){
        throw new RuntimeException("栈为空");
    }
    int oldVal=this.elem[usedSize-1];
    this.usedSize--;
    return oldVal;
}
//获取栈顶元素
    public int peek(){
        if(isEmpty()){
            throw new RuntimeException("栈为空");
        }
        return this.elem[usedSize-1];
    }
    public boolean isEmpty(){
    return this.usedSize==0;
}
}

Pay attention to whether it is a reference or non-reference type when popping the stack

Category 1: Questions about stacking and popping 

 Analysis points:

①The first step is to check the first element and determine the stack sequence

②It is recommended to draw a stack diagram for understanding if you are not familiar with the dialect

Code solution: stack push and pop sequence =/ta/coding-interviews/question-ranking

import java.util.*;

public class Solution {
    public boolean IsPopOrder(int [] pushA,int [] popA) {
        Stack<Integer>stack=new Stack<>();
        int j=0;
      for(int i=0;i<pushA.length;i++){
          stack.push(pushA[i]);
         while(j<popA.length&&(!stack.empty())&&stack.peek()==popA[j]){
              stack.pop();
              j++;
          }

    }return stack.empty();
    }
}

 The second category: infix expression to postfix expression (reverse Polish expression)

Simple problem- solving idea : add parentheses

eg.(5+4)*3-2

①Add parentheses to the expression where each operator is located to the outermost layer

(((5+4)*3)-2)

② Move all symbols outside the corresponding brackets

(((54)+3)*2)-

③The order of numbers is unchanged, remove the parentheses

54+3*2-

think? ? ? How to calculate a value by postfix expression? ? ?

use stack

Problem solving ideas:

① When i points to a number, push the number into the stack. When i points to an operator, put the numbers on the stack to the left and right of it

②Cycle the above steps

 Code implementation: 150. Reverse Polish Expression Evaluation - LeetCode (leetcode-cn.com) https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/

class Solution {
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        for(int i = 0;i < tokens.length;i++) {
            String val = tokens[i];
            if(isOperation(val) == false) {
                //如果不是运算符
                stack.push(Integer.parseInt(val));
            }else {
                //到底是什么运算符
                  int num2 = stack.pop();
                  int num1 = stack.pop();
                switch(val) {
                    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 isOperation(String x) {
        if(x.equals("+") || x.equals("-") ||x.equals("*") ||x.equals("/")) {
            return true;
        }
        return false;
    }
}

The third category:

Effective parentheses for classic topics 

20. Valid Parentheses - LeetCode (leetcode-cn.com) https://leetcode-cn.com/problems/valid-parentheses/

class Solution {
    public boolean isValid(String s) {
        Stack<Character>stack=new Stack<>();
        for(int i=0;i<s.length();i++){
            char ch=s.charAt(i);
            if(ch=='('||ch=='['||ch=='{'){
                //如果是左括号,直接入栈
                stack.push(ch);
            }else{
                //遇到了右括号
                if(stack.empty()){
                    //右括号多
                    System.out.println("右括号多");
                    return false;
                }
                char top=stack.peek();//哪个左括号
                if(top=='{' && ch=='}'||top=='(' && ch==')'||top=='[' && ch==']'){
                    stack.pop();
                }else{
                    //左右括号不匹配
                    System.out.println("左右括号不匹配");
                    return false;
                }
                
            }
        }
        if(!stack.empty()){
            //左括号多
            System.out.println("左括号多");
            return false;
        }
    return true;
    }
}

Minimal Stack of Classic Problems 155. Minimal Stack - LeetCode (leetcode-cn.com) https://leetcode-cn.com/problems/min-stack/Solution ideas:

Relevant code:

class MinStack {
    private Stack<Integer>stack;
     private Stack<Integer>minStack;
    

    public MinStack() {
           stack=new Stack<>();
           minStack=new Stack<>();
    }
    
    public void push(int val) {
      stack.push(val);
      if(!minStack.empty()){
          int top=minStack.peek();
          if(top>=val){
              minStack.push(val);
          }
      }else{
      minStack.push(val);
    }
    }
    public void pop() {
int popVal=stack.pop();
if(!minStack.empty()){
    int top=minStack.peek();
if(popVal==top){
    minStack.pop();
}

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

Guess you like

Origin blog.csdn.net/weixin_58850105/article/details/122509541