21、栈的压入、弹出序列
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
解题思路:
使用一个辅助栈,遍历压入顺序压入辅助栈中,然后判断辅助栈顶元素是否和弹出序列元素是否相同,如果相同,则辅助栈弹出,并且判断弹出序列下一个元素。
C++
class Solution {
public:
bool IsPopOrder(vector<int> pushV,vector<int> popV) {
int s1=pushV.size();
int s2=popV.size();
stack<int> stack_tmp;
if(pushV.empty()||popV.empty()||s1 != s2)
return 0;
for(int i=0,j=0;i<s1;++i)
{ stack_tmp.push(pushV[i]);
while(j<s2 && stack_tmp.top()==popV[j])
{
stack_tmp.pop();
++j;
}
}
return stack_tmp.empty();
}
};
Python
# -*- coding:utf-8 -*-
class Solution:
def IsPopOrder(self, pushV, popV):
# write code here
if (pushV==None or popV==None or len(pushV) != len(popV)):
return False
stack=[]
j=0
for i in pushV:
stack.append(i)
while j<len(popV) and stack[-1]==popV[j]:
stack.pop()
j=j+1
if len(stack)==0:
return True
else:
return False
5、用两个栈实现队列
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
解题思路:
C++
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
if(stack2.empty())
{
while(stack1.size()>0)
{
int data=stack1.top();
stack1.pop();
stack2.push(data);
}
}
int head=stack2.top();
stack2.pop();
return head;
}
private:
stack<int> stack1;
stack<int> stack2;
};
python
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.stack1=[]
self.stack2=[]
def push(self, node):
# write code here
self.stack1.append(node)
def pop(self):
# return xx
if len(self.stack2)==0:
while(len(self.stack1)>0):
elem=self.stack1.pop()
self.stack2.append(elem)
return self.stack2.pop()
20、包含min函数的栈
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
解题思路:
设置一个辅助栈,把每次入栈的最小值都保存在辅助栈min_stack中,data_stack是数据栈。
C++
class Solution {
public:
void push(int value) {
data_stack.push(value);
if(min_stack.empty() || value<min_stack.top())
{
min_stack.push(value);
}
else
{
min_stack.push(min_stack.top());
}
}
void pop() {
data_stack.pop();
min_stack.pop();
}
int top() {
return data_stack.top();
}
int min() {
return min_stack.top();
}
private:
stack<int> data_stack;
stack<int> min_stack;
};
python
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.data_stack=[]
self.min_stack=[]
def push(self, node):
# write code here
self.data_stack.append(node)
if len(self.min_data)!=0:
self.min_data.append(min(node,self.min_data[-1]))
else:
self.min_stack.append(self.min_stack[-1])
def pop(self):
# write code here
if self.data_stack and self.min_stack:
self.data_stack.pop()
self.min_stack.pop()
def top(self):
# write code here
if self.data_stack:
return self.data_stack[-1]
def min(self):
# write code here
if self.min_stack:
return self.min_stack[-1]