栈(stack)的定义:

栈是一种后进先出(LIFO)的线性数据结构

特点:

只能从一端添加元素,也只能从一端(栈顶)取出元素。在计算机中大量应用了栈,如撤销操作,回退操作,编译器中的词法分析器和函数调用实现。

两个操作: push 和pop

栈相关的问题:

包含main函数的栈:

思路:使用两个栈,一个是数据栈用于存储所有数据,另一个是辅助栈用于存储最小值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.stack = []
self.min_stack = []
def push(self, node):
# write code here
self.stack.append(node)
if not self.min_stack or node <= self.min_stack[-1]:
self.min_stack.append(node)
def pop(self):
# write code here
if self.stack[-1] == self.min_stack[-1]:
self.min_stack.pop()
self.stack.pop()
def top(self):
# write code here
return self.stack[-1]
def min(self):
# write code here
return self.min_stack[-1]

栈的压入和弹出序列:

输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)

思路:使用栈模拟这个过程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# -*- coding:utf-8 -*-
class Solution:
def IsPopOrder(self, pushV, popV):
# write code here
if not pushV or not popV or len(pushV)!=len(popV):
return False
stack = []
for i in pushV:
stack.append(i)
while len(stack) and stack[-1]==popV[0]:
stack.pop()
popV.pop(0)
if len(stack):
return False
else:
return True