请你详细为我介绍一下栈 并生成几个相关的实例代码
时间: 2024-04-30 22:23:09 浏览: 8
栈是一种数据结构,它遵循后进先出(LIFO)的原则,也就是最后一个进入栈的元素最先被弹出。
栈有两个基本操作:push和pop。push操作将元素推入栈中,而pop操作将栈顶元素弹出。除此之外,栈还有一个常用的操作peek,它返回栈顶元素的值但不弹出。
下面是几个栈的实例代码:
1. 使用数组实现栈
```
class Stack {
constructor() {
this.items = [];
}
push(element) {
this.items.push(element);
}
pop() {
return this.items.pop();
}
peek() {
return this.items[this.items.length - 1];
}
isEmpty() {
return this.items.length === 0;
}
size() {
return this.items.length;
}
clear() {
this.items = [];
}
}
```
2. 使用链表实现栈
```
class Node {
constructor(element) {
this.element = element;
this.next = null;
}
}
class Stack {
constructor() {
this.top = null;
this.size = 0;
}
push(element) {
const node = new Node(element);
node.next = this.top;
this.top = node;
this.size++;
}
pop() {
if (this.isEmpty()) {
return null;
}
const node = this.top;
this.top = node.next;
this.size--;
return node.element;
}
peek() {
if (this.isEmpty()) {
return null;
}
return this.top.element;
}
isEmpty() {
return this.size === 0;
}
clear() {
this.top = null;
this.size = 0;
}
}
```
3. 判断括号是否匹配的例子
```
function isMatched(expression) {
const stack = new Stack();
for (let i = 0; i < expression.length; i++) {
const char = expression[i];
if (char === '(' || char === '[' || char === '{') {
stack.push(char);
} else if (char === ')' || char === ']' || char === '}') {
if (stack.isEmpty()) {
return false;
}
const topChar = stack.pop();
if ((topChar === '(' && char !== ')') || (topChar === '[' && char !== ']') || (topChar === '{' && char !== '}')) {
return false;
}
}
}
return stack.isEmpty();
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)