Java data structure and algorithm analysis | stack

Time:2022-1-3

GitHub source code sharing

Project home page:https://github.com/gozhuyinglong/blog-demos
Source code of this article:https://github.com/gozhuyinglong/blog-demos/tree/main/java-data-structures

1. Stack

Stack, also known as stack, is a linear table with restricted operations. It is limited that insertion and deletion operations can only be performed at one end, which is called the top of the stack, and the opposite end is called the bottom of the stack.

According to the definition of stack, the most advanced element entering the stack is at the bottom of the stack, and the last element entering the stack is at the top of the stack. The deletion of elements is just the opposite, that is, the deletion order is from the top of the stack to the bottom of the stack

There are only two operations on the stack:

  • Push: also known as pushing or pressing the stack, that is, insert a new element into the stack, which is the new top element of the stack.
  • Out of stack (POP): also known as out of stack, that is, delete (take out) the last element into the stack from the top of the stack, and its adjacent elements become new top elements.

Java data structure and algorithm analysis | stack

The stack is an ordered list of Filo – first in last out. The stack model is described in the figure above. We have only a few operations on the stackpushandpop, the top element of the stack is the only visible element of the stack.

2. Code implementation

Since the stack is a table, any method that implements a table can implement the stack. Obviously, we used it before《array》And《Linked list》Stack can be implemented. The following code is a stack implemented using an array.

sizeIndicates the size of the elements in the stack. The top element of the stack is elementdata [size – 1], and the bottom element is elementdata [0]. Execute size + + when entering the stack and size + + when exiting–

public class StackDemo {

    public static void main(String[] args) {

        System. out. Println ("------------------ inbound");
        Stack<String> stack = new Stack<>(10);
        stack.push("a");
        stack.push("b");
        stack.push("c");
        stack.push("d");
        stack.push("e");
        stack.print();

        System. out. Println ("element size:" + stack. Size());
        System. out. Println ("stack capacity:" + stack. Capacity());

        System. out. Println ("------------------ outbound");
        System. out. Println ("outbound element:" + stack. Pop());
        System. out. Println ("outbound element:" + stack. Pop());
        stack.print();
        System. out. Println ("element size:" + stack. Size());
        System. out. Println ("stack capacity:" + stack. Capacity());
    }

    private static class Stack<E> {
        private int size; //  Element size
        private final int capacity; //  Stack capacity
        transient Object[] elementData; //  Element data

        public Stack(int capacity) {
            if (capacity <= 0) {
                throw new IllegalArgumentException("Illegal Capacity: " + capacity);
            } else {
                this.capacity = capacity;
                elementData = new Object[capacity];
            }
        }

        /**
         *Gets the element size of the stack
         *
         * @return
         */
        public int size() {
            return size;
        }

        /**
         *Gets the capacity of the stack
         *
         * @return
         */
        public int capacity() {
            return capacity;
        }

        /**
         *Stack
         *
         * @param e
         * @return
         */
        public boolean push(E e) {
            if (size >= capacity) {
                return false;
            }
            elementData[size++] = e;
            return true;
        }

        /**
         *Out of stack
         *
         * @return
         */
        public E pop() {
            if (size <= 0) {
                return null;
            }
            return (E) elementData[--size];
        }

        /**
         *Print element data
         */
        public void print() {
            System. out. Print ("station element:");
            for (int i = 0; i < size; i++) {
                System.out.printf("%s\t", elementData[i]);
            }
            System.out.println();
        }
    }
}

Output results:

-------------------Inbound
Station elements: a b c d e    
Element size: 5
Stack capacity: 10
-------------------Outbound
Outbound element: e
Outbound element: D
Station elements: A, B, C    
Element size: 3
Stack capacity: 10

3. Stack application – balance symbol

When the compiler checks the syntax error of the program, it often lists hundreds of lines of diagnosis on the compiler due to the lack of a symbol (such as missing a curly bracket), but the real error is not found. In this case, it would be nice if a tool could detect that parentheses must appear in pairs, which can be solved by using the stack.

The following code uses Java’s ownStackClass. character string [ ( ) ] Is legal, and [ ( ] ) Is wrong.

Code implementation:

public class StackDemoBalancedChar {

    public static void main(String[] args) {

        BalancedChar balancedChar = new BalancedChar();
        String str = "[()][{}][][((()))]";
        boolean ok = balancedChar.isOk(str);
        System. out. Printf ("string:% s \ t --- >% s", STR, OK);
    }

    private static class BalancedChar {
        Private Final char [] openarray = {'(', '[', '{'}; // left parenthesis
        private final char[] closeArray = {')', ']', '}'}; //  Right parenthesis

        /**
         *Determine whether the string is correct
         *
         * @param str
         * @return
         */
        public boolean isOk(String str) {
            //Use the stack class that comes with Java
            Stack<Character> stack = new Stack<>();

            boolean ok = true; //  Determine whether the string is correct

            for (char c : str.toCharArray()) {

                //If not, ignore
                if (!isBalancedChar(c)) {
                    continue;
                }

                //If it is an open parenthesis, it is put on the stack
                if (isOpen(c)) {
                    stack.push(c);
                    continue;
                }

                //If it is a right parenthesis and the stack is empty, an error is reported
                if (stack.empty()) {
                    ok = false;
                    break;
                }
                //If it is a right parenthesis, take an element from the stack and judge whether it is a pair with the current element. If it is not a pair, an error is reported
                Character open = stack.pop();
                if (!isTwain(open, c)) {
                    ok = false;
                }
            }

            return ok && stack.empty();
        }

        /**
         *Is it an open parenthesis
         *
         * @param c
         * @return
         */
        public boolean isOpen(char c) {
            return inArray(openArray, c);
        }

        /**
         *Is it a right parenthesis
         *
         * @param c
         * @return
         */
        public boolean isClose(char c) {
            return inArray(closeArray, c);
        }

        /**
         *Is it a balancer
         */
        public boolean isBalancedChar(char c) {
            return isOpen(c) || isClose(c);
        }

        /**
         *Is it in the array
         *
         * @param charArray
         * @param c
         * @return
         */
        public boolean inArray(char[] charArray, char c) {
            for (char c1 : charArray) {
                if (c1 == c) {
                    return true;
                }
            }
            return false;
        }

        /**
         *Is it a pair of balancers
         *
         * @param open
         * @param close
         * @return
         */
        public boolean isTwain(char open, char close) {
            switch (open) {
                case '(':
                    if (close == ')') {
                        return true;
                    }
                case '[':
                    if (close == ']') {
                        return true;
                    }
                case '{':
                    if (close == '}') {
                        return true;
                    }
                default:
                    return false;
            }
        }

    }
}

Output results:

String: [()] [{}] [] [(())] --- > true

Get more

Wechat search: Menon stayup
Personal homepage:https://gozhuyinglong.github.io