问题1、两个栈实现队列
class Queue
{
public:
//入队
void Push(const int value){
s1.push(value);
}
//出队
int Pop(){
while (s1.size())
{
s2.push(s1.top());
s1.pop();
}
int temp = s2.top();
if (s2.empty())
{
throw exception("no data");
}
s2.pop();
return temp;
}
private:
stack<int> s1;
stack<int> s2;
};
问题2、两个队列实现栈
class Stack
{
public:
void Push(const int value){
q1.push(value);
}
int Pop(){
while (q1.size()>1)
{
q2.push(q1.front());
q1.pop();
}
int temp = q1.front();
q1.pop();
while (!q2.empty())
{
q1.push(q2.front());
q2.pop();
}
return temp;
}
private:
queue<int> q1;
queue<int> q2;
};
问题3、定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的min函数。在该栈中,调用min、push及pop的时间复杂度均为O(1)
//需要使用一个辅助栈,用来保存当前数组的最小值
class Stack
{
public:
void push(const int data){
s[top++]=data;
if (top==1)
s0[top0++]=data;
else
{
int temp = s0[top0-1];
if (data<temp)
s0[top0++]=data;
else
s0[top0++] =temp;
}
}
int pop(){
if (top==0)
throw exception("no data");
s0[--top0]; //注意:出栈的时候辅助栈也要同步出栈
return s[--top];
}
int min(){
if (top0==0)
throw exception("no data");
return s0[top0-1];
}
public:
int s[20];
int s0[20];
int top=0;
int top0=0;
};
问题4、根据入栈序列,求出所有可能的出栈序列
//1.求出入栈序列的全排列
//2.判断是否满足出栈的要求
//加入入栈先后依次为:1,2,3,4,5
void Permutation(int a[],int start,int len){
if(start==len-1){
for(int i=0;i<len;i++)
cout<<a[i]<<" ";
cout<<endl;
}
for(int i=start;i<len;i++){
swap(a[i],a[start]);
Permutation(a,start+1,len);
swap(a[i],a[start]);
}
}
//2.判断数组是否是正确的出栈队列
#include<iostream>
#include<algorithm>
#include<stack>
#include<queue>
using namespace std;
bool check(int a[],int len){
int b=0;
for (int i = 0; i < len-1; i++){
int m=0;
for (int j = i + 1; j<len; j++){
if (a[i]>a[j])
{
if (m == 0){
b = a[j]; //记录当前第一个小的,以便和后面的比较
m++;
}
else
{
if (a[j]>m) //如果后面的有递增情况发生,则不符合,直接返回false
return false;
else //否则,更新当前最小的值继续向后推进比较
b = a[j];
}
}
}
}
return true;
}
void Permutation(int a[], int start, int len){
if (start == len - 1){
if (check(a, len)){
for (int i = 0; i<len; i++)
cout << a[i] << " ";
cout << endl;
}
}
for (int i = start; i<len; i++){
swap(a[i], a[start]);
Permutation(a, start+1, len);
swap(a[i], a[start]);
}
}
int main(){
int a[] = {1,2,3,4};
Permutation(a,0,4);
/*
系统自带的全排列公式
while(next_permutation(a,a+4))
{
//a不包括原型
for(int i=0;i<4;i++)
cout<<a[i]<<" ";
cout<<endl;
}
*/
system("pause");
return 0;
}