Java implementation stack detailed explanation and example code

Stack is a list that restricts insertion and deletion to only one position. This position is the end of the list, which is called the top of the stack. The basic operations of the stack are push and pop. The former is insertion and the latter is deletion.

The stack is also a FIFO table.

There are two implementations of stack, one is to use array and the other is to use linked list.

Application of stack

Balance symbol

Given a string of code, we check whether the parentheses in this code conform to the syntax.

For example: [{()}] this is legal, but [{]} () is illegal.

The following is the test code:

Postfix Expression

For example, one of the following inputs calculates the corresponding result,

3 + 2 + 3 * 2 = ?

This will produce different results in different calculation order. If the calculation result is 16 from left to right, and if it is 11 according to mathematical priority.

If the infix expression above is converted to a suffix expression:

3 2 + 3 2 * +

If you use a suffix expression to calculate the value of this expression, it will be very simple. You only need to use a stack.

Whenever you encounter a number, put the number on the stack.

Whenever an operator is encountered, two elements pop up and are put on the stack after being calculated according to the operator.

The only element of the final pop-up stack is the calculation result.

Convert infix expression to suffix expression

Suppose only the expressions +, -, *, /, () are run. And the expression is legal.

The suffix expression after a + b * C - (d * e + F) / g conversion is as follows:

a b c * + d e * f + g / -

The steps to use the suffix in the stack are as follows:

Through this article, I hope you can master the knowledge of Java stack. Thank you for your support to this site!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>