Java data structure - stack

Stack in computer

We introduce the concept of stack in life into the computer, which is a place for data to rest. It is a data structure. Data can enter and exit the stack.
The data structure FILO (first in and then out) [overlapping, first down above] is different from the FIFO (first in and first out) in the queue [water pipe flow, which can only be output from one end and deleted in a fixed direction at one end]
Stack is a special linear table that can only be inserted and deleted at one end. It stores data according to the principle of first in and last out. The first entered data is pressed into the bottom of the stack, and the last data is at the top of the stack. When data needs to be read, data will pop up from the top of the stack (the last data will be read out first). We call the action of data entering the stack as pressing the stack, and the action of data leaving the stack as bouncing the stack.


Code implementation (through linked list)

 

public class MyStack<T> implements Iterable<T>{
    Node head ;
    int N;
    public MyStack(){
        this.head = new Node(null,null);
        this.N = 0;
    }


    class Node{
        T item;
        Node next;
        public Node(T item ,Node next){
            this.item = item;
            this.next =next;
        }
    }
    public void clear(){
        head.next = null;
        N = 0;
    }
    public boolean isEmpty(){
        return N==0;
    }

    public int size(){
        return this.N;
    }

    public T pop(){
        Node oldNext = this.head;
        if(oldNext == null){
            return null;
        }
        this.head.next = oldNext.next.next;
        this.N --;
        return oldNext.item;
    }

    public void push(T t){
        Node curr = this.head.next;
        Node newNode = new Node(t, curr);
        this.head.next = newNode;
    }
    @Override
    public Iterator<T> iterator() {
        return new MyIterator();
    }
    private class MyIterator implements Iterator<T>{
        Node node = head ;
        @Override
        public boolean hasNext() {
            return node.next!=null;
        }

        @Override
        public T next() {
            node = node.next;
            return node.item;
        }
    }
}

Use case of stack (inverse Polish expression)

The evaluation problem of inverse Polish expression is a kind of problem often encountered in our computer. To study and understand this problem, we must first find out what is inverse Polish expression? To understand the inverse Polish expression, we have to start with infix expression.

Infix expression:

  • Infix expressions are expressions used in our daily life, such as 1 + 3 * 2,2 - (1 + 3), etc. the characteristics of infix expressions are: binary operators are always placed between two operands;

  • Infix expression is people's favorite expression because it is simple and easy to understand. But this is not the case for computers, because the operation order of infix expressions is not regular. Different operators have different priorities. If the computer executes infix expressions, it needs to parse the expression semantics and do a lot of priority related operations.

Inverse Polish expression (suffix expression): inverse Polish expression is an expression representation method first proposed by Polish logician J. lukasewicz in 1929. The characteristic of suffix expression is that the operator is always placed after the operands related to it.

Infix expression and inverse Polish expression conversion table:

 

Hypothetical requirements:

Given an array of inverse Polish expressions containing only four operations of addition, subtraction, multiplication and division, the result of the inverse Polish expression is obtained.
Infix expression: 5 * (21-3) + 21 / 7
Inverse Polish expression: 5 21 3 - * 21 7 /+

1. Create a stack object expression to store operands;
2. Traverse the inverse Polish expression from left to right to get each string;
3. Judge whether the string is an operator. If not, press the operand into the oprands stack;
4. If it is an operator, two operands o1,o2 will pop up from the expression stack;
5. Use this operator to calculate o1 and o2 to obtain the result;
6. Press the result into the expression stack;
7. After traversal, take out the final result in the stack and return it;

code implementation

class MyStackTest{
    public static void main(String[] args) {
        int i = 5 * (21 - 3) + 21 / 7;
        System.out.println("Infix expression calculation result:"+i);
        String[] str = {"5", "21", "3", "-", "*", "21", "7", "/", "+"};
        Integer calculation = calculation(str);
        System.out.println("Calculation result of inverse Polish expression:"+calculation);


    }
    public static Integer calculation(String[] arr){
        MyStack<Integer> expression = new MyStack<>();
        for (String s : arr) {
            Integer o1,o2,result;
            switch (s){
                case "+":
                    o1 = expression.pop();
                    o2 = expression.pop();
                    result = o2 + o1;
                    expression.push(result);
                    break;
                case "-":
                    o1 = expression.pop();
                    o2 = expression.pop();
                    result = o2 - o1;
                    expression.push(result);
                    break;
                case "*":
                    o1 = expression.pop();
                    o2 = expression.pop();
                    result = o2 * o1;
                    expression.push(result);
                    break;
                case "/":
                    o1 = expression.pop();
                    o2 = expression.pop();
                    result = o2 / o1;
                    expression.push(result);
                    break;
                default:
                    expression.push(Integer.parseInt(s));
            }
        }
        return expression.pop();
    }
}

Tags: Java data structure

Posted on Thu, 28 Oct 2021 02:38:26 -0400 by expertis