Stack¶
Stacks and queues are dynamic sets in which the element removed from the set by Delete
operation is prespecified.
In a stack
, the element deleted from the set is the most recently inserted: the stack implements a last-in, first-out
or LIFO
, policy.
The Insert
operation on a stack is often called Push
, and the Delete
operation, which does not take an element, is often called Pop
. These names are allusions to physical stacks, such as the spring-loaded stacks of plates used in cafeteriass. The order in which plates are popped from the stack is the reverse of the order in which they were pushed onto the stack, since only the top plate is accessible.
Problems¶
Implementation¶
This kind of problems mainly contains use other data structures of:
- array
- linked list
- queue
to implement a stack
class.
Syntax Parsing¶
This kind of problems are mainly about the few elements at the end of lists, for example:
- Paretheses matching, which delete the parentheses matched;
- Path finding, which delete the elements at the back if
..
occurs.
problems:
Expression Evaluation¶
The tytical problem of this is the calculator. We usually solve this with two stacks:
number
stack, which records all numbers to be calculated;operator
stack, which stores operators((, ), +, -, *, /
) in increasing grade,(, )
is 0,+, -
is 1,*, /
is 2.
The general frame is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
- 150. Evaluate Reverse Polish Notation
- 224. Basic Calculator
- 227. Basic Calculator II
- 772. Basic Calculator III
Monotonous Stack¶
Monotonous stack make sure that all elements from bottom to top are in increasing or decreasing order. To do so, use the loop:
1 2 3 4 5 |
|
Sometimes we want to choose n
number form a list, the relative order of the digits from the list should be preserved and make the new number with the length of n
maximum.
This could also be created with monotonous stack:
1 2 3 4 5 6 7 |
|