1.问题描述
(1)包含Min函数的栈
定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
(2)栈的压入弹出序列
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的
2.思路解析
(1)添加辅助栈,记录栈的最小元素。每次入栈时,待入栈元素比辅助栈栈顶元素小或相等,则加入辅助栈;每次出栈时,待出栈元素等于辅助栈栈顶元素时,辅助栈元素出栈。
(2)先把元素入栈,入栈的时候如果待入栈元素和弹出序列的待比较元素相等,则该元素不入栈,弹出序列的Index+1继续看下一个待压入元素,直到所有元素都已入栈。若此时弹出序列不为空,则依次比较弹出序列和栈顶元素。
3.python代码
(1)包含min函数的栈
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.stack = []
self.min_stack = []
def push(self, node):
# write code here
if not self.min_stack or self.min_stack[-1]>=node:
self.min_stack.append(node)
self.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]
(2)栈的压入弹出序列
# -*- coding:utf-8 -*-
class Solution:
def IsPopOrder(self, pushV, popV):
# write code here
length, index,stack = len(pushV),0,[]
for num in pushV:
if num!=popV[index]:
stack.append(num)
else:
index += 1
if index==length:
return True
else:
for i in range(index, length):
if stack[-1]!= popV[i]:
return False
else:
stack.pop()
return True