栈
先进后出;push;pop
两种存储表示方式:顺序栈,链式栈
用数组实现一个顺序栈
1 | # coding:utf-8 |
用链表实现一个链式栈
使用head表示栈顶
1 | class Node: |
编程模拟实现一个浏览器的前进、后退功能
1 | # coding:utf-8 |
对应的 LeetCode 练习题
Valid Parentheses(有效的括号)
英文版:https://leetcode.com/problems/valid-parentheses/
中文版:https://leetcode-cn.com/problems/valid-parentheses/
1 | class Solution(object): |
Longest Valid Parentheses(最长有效的括号)
英文版:https://leetcode.com/problems/longest-valid-parentheses/
中文版:https://leetcode-cn.com/problems/longest-valid-parentheses/
参考:https://leetcode.com/problems/longest-valid-parentheses/solution/
改方法使用栈,先在栈底放入-1,然后放各个括号索引
1 | class Solution(object): |
测试用例
1 | s = Solution() |
Evaluate Reverse Polish Notatio(逆波兰表达式求值)
英文版:https://leetcode.com/problems/evaluate-reverse-polish-notation/
中文版:https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/
题中指明逆波兰式总是有效的,因此无需判定有效,直接使用栈解答
1 | class Solution: |
python除法可参考:python – 整数除以负数
更简洁的写法(耗时更长):
1 | class Solution: |
部分测试用例:
1 | s = Solution() |
队列
用数组实现一个顺序队列
1 | # coding:utf-8 |
用链表实现一个链式队列
1 | # coding:utf-8 |
实现一个循环队列
1 | class Queue: |
对应的 LeetCode 练习题
Circular Deque(设计一个双端队列)
英文版:https://leetcode.com/problems/design-circular-deque/
中文版:https://leetcode-cn.com/problems/design-circular-deque/
1 | class MyCircularDeque(object): |
部分测试用例
1 | circularDeque = MyCircularDeque(3) # 设置容量大小为3 |
Sliding Window Maximum(滑动窗口最大值)
英文版:https://leetcode.com/problems/sliding-window-maximum/
中文版:https://leetcode-cn.com/problems/sliding-window-maximum/
链表
实现单链表、循环链表、双向链表,支持增删操作
1 | # coding: utf-8 |
实现单链表反转
1 | # coding: utf-8 |
实现两个有序的链表合并为一个有序链表
1 | def Merge(self, pHead1, pHead2): |
实现求链表的中间结点
1 | # coding: utf-8 |
对应的 LeetCode 练习题
Linked List Cycle I(环形链表)
英文版:https://leetcode.com/problems/linked-list-cycle/
中文版:https://leetcode-cn.com/problems/linked-list-cycle/