1.栈的初始化等
代码
#include<iostream>
using namespace std;
#define MaxSize 50
typedef int ElemType;
typedef struct{
ElemType data[MaxSize];
int top;
}SqStack;
//1.初始化栈
void init(SqStack &S)
{
S.top=-1;
}
//2.判断栈空
int isEmpty(SqStack S)
{
if(S.top==-1)return 1;
return 0;
}
//3.进栈
bool push(SqStack &S,ElemType x)
{
if(S.top==MaxSize-1)return false;
S.data[++S.top]=x;
return true;
}
//4.出栈
bool pop(SqStack &S,ElemType&x)
{
if(isEmpty(S))return false;
x=S.data[S.top--];
return true;
}
//5.读栈顶元素
bool top(SqStack S,ElemType&x)
{
if(isEmpty(S))return false;
x=S.data[S.top];
return true;
}
int main()
{
SqStack stack;
init(stack);
int x;
cout<<"输入一个十进制数"<<endl;
cin>>x;
while(x!=0)
{
push(stack,x%8);
x=x/8;
}
while(!isEmpty(stack))
{
pop(stack,x);
cout<<x;
}
return 0;
}
//判断IO(进栈出栈)序列是否合法
bool isRightful(char *str)
{
int count=0;
for(int i=0;str[i]!='\0';i++)
{
if(str[i]=='I')
{
count++;
}
else if(str[i]=='O')
{
if(count==0)
{
return false;
}
else
{
count--;
}
}
else
{
return false;
}
}
return count==0;
}
2.加一个最小值栈
代码
typedef int ElemType
#define MaxSize=100
typedef struct{
ElemType data[MaxSize];
int top;
}SqStack;
typedef struct{
SqStack eStack;
SqStack minStack;
}MEStack;
void init(MEStack &s)
{
s.eStack.top=-1;
s.minStack.top=-1;
}
bool top(MEStack s,ElemType &x1,ElemType &x2)
{
if(s.eStack.top==-1||s.minStack.top==-1)
{
return false;
}
x1=s.eStack.data[s.eStack.top];
x2=s.minStack.data[s.minStack.top];
return true;
}
bool push(MEStack s,ElemType e)
{
if(s.eStack.top==MaxSize-1||s.minStack.top==MaxSize-1)
{
return false;
}
s.eStack.data[++s.eStack.top]=e;
ElemType x1,x2;
top(s,x1,x2);
s.minStack.data[++s.minStack.top]=min(e,x2);
return true;
}
bool pop(MEStack s,ElemType &x1,ElemType &x2)
{
if(s.eStack.top==-1||s.minStack.top==-1)
{
return false;
}
x1=s.eStack.data[s.eStack.top--];
x2=s.minStack.data[s.minStack.top--];
return true;
}
bool getMin(MEStack &s,ElemType &min)
{
if(s.minStack.top==-1)
{
return false;
}
min=s.minStack.data[s.minStack.top];
}
3.设有两个栈S1,S2都采用顺序栈,并共享一个存储区[0..MaxSize-1],设计共享栈
思想:
1.栈空:S1初始为空,top1=-1,S2初始为空,top2==MaxSize
2.栈满:top1与top2相邻
S1入栈:栈不满的情况下,先top1++,再存储元素
S2入栈:栈满的情况下,先top2–,再存储元素
#define MaxSize 5
typedef int ElemType;
typedef struct{
ElemType stack[MaxSize];
int top[2];
}ShareStack;
void initShareStack(ShareStack &S)
{
S.top[0]=-1;
S.top[1]=MaxSize;
}
bool push(ShareStack &S,int i,ElemType e)
{
if(i<0||i>1)
{
return false;
}
//栈满
if(S.top[0]+1==S.top[1])
{
return false;
}
if(i==0)
{
S.stack[++S.top[0]]=e;
}
else if(i==1)
{
S.stack[--S.top[1]]=e;
}
return true;
}
bool pop(ShareStack &S,int i,ElemType&x)
{
if(i<0||i>1)return false;
//栈空
if(i==0&&S.top[0]==-1)return false;
if(i==1&&S.top[1]==MaxSize) return false;
if(i==0)
{
x=S.data[S.top[0]--];
}
else if(i==1)
{
x=S.data[S.top[1]++];
}
return true;
}