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]