Concepts and Features
concept
A stack is also a data structure similar to a list. It’s a linear table with limited operations.
The characteristics of
Can only be added or removed at the top of the stack.
2. Common operations are push and POP
3. This feature is called LIFO (last-in-first-out)
Code implementation
In fact, we can directly simulate the operation mode of the stack in the array, but in order to facilitate your understanding, we will encapsulate the stack.
Thinking analytical
- Implement a Stack class
- Push implementation
- Pop out of the stack implementation
- Look at the top of the stack element peek implementation
Code implementation
class Stack {
value: any[] = [];
top: number = 0;
push(el: any) {
this.value[this.top] = el;
this.top++;
}
pop() {
const temp = this.value[this.top - 1];
this.value.length = --this.top;
return temp;
}
peek() {
return this.value[this.top - 1]; }}const a = new Stack();
a.push(1);
a.push(2);
a.push(3);
console.log(a.peek());
console.log(a.value);
console.log(a.pop());
console.log(a.value);
Copy the code
Array type directly emulated
const arr = [];
arr.push(aa);
arr.pop();
Copy the code
Brush question further
Leetcode -20. Valid parentheses – easy to get started