|
| 1 | +# 栈 |
| 2 | + |
| 3 | +## 性质 |
| 4 | + |
| 5 | +### 性质1: LIFO |
| 6 | + |
| 7 | +提供一种基于数据停留在集合中的时间来排序的方式,时长短的在顶部,反之在底部。 |
| 8 | + |
| 9 | +### 性质2: 反转(盗梦空间) |
| 10 | + |
| 11 | +## ADT 与实现 |
| 12 | + |
| 13 | +### ADT |
| 14 | + |
| 15 | +- Stack()创建一个空栈。它不需要参数,且会返回一个空栈。 |
| 16 | +- push(item)将一个元素添加到栈的顶端。它需要一个参数 item,且无返回值。 |
| 17 | +- pop()将栈顶端的元素移除。它不需要参数,但会返回顶端的元素,并且修改栈的内容。 |
| 18 | +- peek()返回栈顶端的元素,但是并不移除该元素。它不需要参数,也不会修改栈的内容。 |
| 19 | +- isEmpty()检查栈是否为空。它不需要参数,且会返回一个布尔值。 |
| 20 | +- size()返回栈中元素的数目。它不需要参数,且会返回一个整数。 |
| 21 | + |
| 22 | +![[Pasted image 20220102214934.png]] |
| 23 | + |
| 24 | +### 实现 |
| 25 | + |
| 26 | +#### 要点 |
| 27 | + |
| 28 | +1. “有序”排列 |
| 29 | +2. 考虑栈顶使用列表的哪个位置 |
| 30 | + |
| 31 | +#### 基于列表尾部/头部 |
| 32 | + |
| 33 | +```python |
| 34 | +class MyStack: |
| 35 | + def __init__(self): |
| 36 | + self.items = [] |
| 37 | + |
| 38 | + def is_empty(self) -> bool: |
| 39 | + return len(self.items) == 0 |
| 40 | + |
| 41 | + # def push(self, item): |
| 42 | + # self.items.append(item) |
| 43 | + def push(self, item): |
| 44 | + self.items.insert(0, item) |
| 45 | + |
| 46 | + # def pop(self): |
| 47 | + # return self.items.pop() |
| 48 | + def pop(self): |
| 49 | + return self.items.pop(0) |
| 50 | + |
| 51 | + # 如何使用切片和解构返回顶部元素呢? |
| 52 | + def peek(self): |
| 53 | + return self.items[len(self.items) - 1] |
| 54 | + |
| 55 | + def size(self): |
| 56 | + return len(self.items) |
| 57 | +``` |
| 58 | + |
| 59 | + |
| 60 | +## 经典案例 |
| 61 | + |
| 62 | +### 进制转化 |
| 63 | + |
| 64 | +### (前、中、后)序表达式转化 |
| 65 | + |
| 66 | + |
| 67 | +- [ ] [20. 有效的括号](https://leetcode-cn.com/problems/valid-parentheses/) |
| 68 | +- [ ] [853. 车队](https://leetcode-cn.com/problems/car-fleet/) |
| 69 | +- [ ] [735. 行星碰撞](https://leetcode-cn.com/problems/asteroid-collision/) |
| 70 | + |
| 71 | +盗梦空间 |
| 72 | + |
| 73 | + [1047. 删除字符串中的所有相邻重复项](https://leetcode-cn.com/problems/remove-all-adjacent-duplicates-in-string/) |
| 74 | + [150. 逆波兰表达式求值](https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/) |
| 75 | +[736. Lisp 语法解析](https://leetcode-cn.com/problems/parse-lisp-expression/) |
| 76 | +[224. 基本计算器](https://leetcode-cn.com/problems/basic-calculator/) |
| 77 | + [241. 为运算表达式设计优先级](https://leetcode-cn.com/problems/different-ways-to-add-parentheses/) |
| 78 | + |
| 79 | + |
| 80 | +## 课后思考 |
| 81 | + |
| 82 | +### 工业应用 |
| 83 | + |
| 84 | +[[浏览器历史管理]] |
| 85 | +- [ ] [1472. 设计浏览器历史记录](https://leetcode-cn.com/problems/design-browser-history/) |
| 86 | + |
| 87 | +#### HTML词法解析 |
| 88 | + |
| 89 | +[[DOM检查 ?react 解析器?开源工具?]] |
| 90 | + |
| 91 | + - [ ] [591. 标签验证器](https://leetcode-cn.com/problems/tag-validator/) |
| 92 | + |
| 93 | +### 高级话题 |
| 94 | + |
| 95 | +[[操作系统层面的调用栈管理?]] |
0 commit comments