栈
#include<bits/stdc++.h>
using namespace std;
#define MaxSize 100
//定义
typedef struct{
char data[MaxSize];
int top;
}SqStack;
//初始化
void InitStack(SqStack &S)
{
S.top=-1;
}
//判栈空
bool StackEmpty(SqStack &S)
{
if(S.top==-1)
return true;
else
return false;
}
//入栈
void Push(SqStack &S,char x)
{
if(S.top==MaxSize-1)
{
cout<<"栈满"<<endl;
}
else
{
S.top++;
S.data[S.top]=x;
}
}
//出栈
void Pop(SqStack &S,char x)
{
if(S.top==-1)
{
cout<<"栈空"<<endl;
}
else
{
x=S.data[S.top];
S.top--;
}
}
//读栈顶元素
void GetTop(SqStack &S)
{
if(S.top==-1)
{
cout<<"NULL"<<endl;
}
else
{
cout<<S.data[S.top]<<endl;
}
}
//括号匹配
bool Check(char *s)
{
SqStack S;
InitStack(S);
int i=0;
while(s[i]!='\0')
{
switch(s[i])
{
char x;
case'(':Push(S,'(');break;
case'[':Push(S,'[');break;
case'{':Push(S,'{');break;
case')':Pop(S,x);
if(x!='(')
return false;
break;
case']':Pop(S,x);
if(x!='[')
return false;
break;
case'}':Pop(S,x);
if(x!='{')
return false;
break;
default:
break;
}
i++;
}
if(!StackEmpty(S))
{
cout<<"匹配失败"<<endl;
return false;
}
else
{
cout<<"匹配成功"<<endl;
return true;
}
}
int main()
{
char *s="([{}])";
Check(s);
}
顺序队
#include<bits/stdc++.h>
using namespace std;
#define MaxSize 100
//定义
typedef struct{
int data[MaxSize];
int fro,rear;
}SqQueue;
//初始化
void InitQueue(SqQueue &Q)
{
Q.fro=Q.rear=0;
}
//判队空
bool isEmpty(SqQueue Q)
{
if(Q.fro==Q.rear)
{
return true;
}
else
{
return false;
}
}
//入队
void EnQueue(SqQueue &Q,int x)
{
if((Q.rear+1)%MaxSize==Q.fro)
{
cout<<"队满"<<endl;
}
Q.data[Q.rear]=x;
Q.rear=(Q.rear+1)%MaxSize;
}
//出队
void DeQueue(SqQueue &Q,int &x)
{
if(Q.rear==Q.fro)
{
cout<<"队空"<<endl;
}
x=Q.data[Q.fro];
Q.fro=(Q.fro+1)%MaxSize;
}
链队
#include<bits/stdc++.h>
using namespace std;
//定义
typedef struct LNode{
int data;
LNode *next;
}LNode,*LinkList;
typedef struct{
LNode *fro,*rear;
}LinkQueue;
//初始化
void InitQueue(LinkQueue &Q)
{
Q.fro=Q.rear=(LinkList)malloc(sizeof(LNode));
Q.fro->next=NULL;
}
//判队空
bool isEmpty(LinkQueue Q)
{
if(Q.fro==Q.rear)
{
return true;
}
else
{
return false;
}
}
//入队
void EnQueue(LinkQueue &Q,int x)
{
LNode *s=(LNode*)malloc(sizeof(LNode));
s->data=x;
s->next=NULL;
Q.rear->next=s;
Q.rear=s;
}
//出队
void DeQueue(LinkQueue &Q,int &x)
{
if(Q.fro==Q.rear)
{
cout<<"空队"<<endl;
}
LNode *p=Q.fro->next;
x=p->data;
Q.fro->next=p->next;
if(Q.rear==p)
Q.rear=Q.fro;
free(p);
}
//打印
void print(LinkQueue &Q)
{
LNode *p=Q.fro->next;
while(p!=NULL)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
int main()
{
LinkQueue q;
InitQueue(q);
int x;
EnQueue(q,1);
EnQueue(q,2);
EnQueue(q,3);
EnQueue(q,4);
EnQueue(q,5);
print(q);
DeQueue(q,x);
DeQueue(q,x);
print(q);
}