一、栈
n个不同元素进栈,出栈元素不同排列的个数为。
栈的顺序存储
#include <iostream>
using namespace std;
typedef int ElemType;
#define MaxSize 50
typedef struct
{
ElemType data[MaxSize];
int top;
}SqStack;
//初始化
void InitStack(SqStack &s)
{
s.top=-1;
}
//判空
bool StackEmpty(SqStack s)
{
if(s.top==-1)
return true;
return false;
}
//进栈
bool Push(SqStack &s,ElemType x)
{
if(s.top==MaxSize-1)
return false;
s.data[++s.top]=x;
return true;
}
//出栈
bool Pop(SqStack &s,ElemType &x)
{
if(StackEmpty(s))
return false;
x=s.data[s.top--];
return true;
}
//读栈顶元素
bool GetTop(SqStack s,ElemType &x)
{
if(StackEmpty(s))
return false;
x=s.data[s.top];
return true;
}
int main()
{
SqStack s;
InitStack(s);
Push(s,10);
ElemType y=1;
GetTop(s,y);
cout<<y;
return 0;
}
栈的链式存储
二、队列
数组a[n]的下标范围为0~n-1。若写成a[0...n]说明下标范围为0~n;
队列的顺序存储
队列的链式存储
三、栈和队列的应用
栈:括号匹配
请输入英文括号
#include <iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
typedef char ElemType;
#define MaxSize 50
typedef struct
{
ElemType data[MaxSize];
int top;
}SqStack;
//初始化
void InitStack(SqStack &s)
{
s.top=-1;
}
//判空
bool StackEmpty(SqStack s)
{
if(s.top==-1)
return true;
return false;
}
//进栈
bool Push(SqStack &s,ElemType x)
{
if(s.top==MaxSize-1)
return false;
s.data[++s.top]=x;
return true;
}
//出栈
bool Pop(SqStack &s,ElemType &x)
{
if(StackEmpty(s))
return false;
x=s.data[s.top--];
return true;
}
//读栈顶元素
bool GetTop(SqStack s,ElemType &x)
{
if(StackEmpty(s))
return false;
x=s.data[s.top];
return true;
}
bool work(char ss[])
{
SqStack s;
InitStack(s);
int length=strlen(ss);
for(int i=0;i<length;i++)
{
if(ss[i]=='('||ss[i]=='[')
{
Push(s,ss[i]);
}
else
{
char q;
Pop(s,q);
if(ss[i]==')'&&q!='(')
return false;
if(ss[i]==']'&&q!='[')
return false;
}
}
return StackEmpty(s);
}
int main()
{
char ss[MaxSize];
scanf("%s",ss);
if(work(ss))
printf("成功");
else printf("失败");
return 0;
}