//栈在括号匹配中的应用
#include<stdio.h>
#include<stdlib.h>
typedef int Position;
typedef char ElementType;
struct SNode{
ElementType *Data;
Position Top;
int MaxSize;
};
typedef struct SNode *Stack;
Stack CreatStack(int MaxSize);
bool IsFull(Stack S);
bool Push(Stack S,ElementType X);
bool IsEmpty(Stack S);
ElementType Pop(Stack S);
bool bracketCheck(char str[],int length)
{
Stack S=CreatStack(10);
for(int i=0;i<length;i++){
if(str[i]=='('||str[i]=='['||str[i]=='{')
Push(S,str[i]);
else{
if(IsEmpty(S))
return false;
char topElem=Pop(S);
// if(str[i]==')'&&topElem!='(')
// return false;
// if(str[i]==']'&&topElem!='[')
// return false;
// if(str[i]=='}'&&topElem!='{')//str[i]等于这三种,再把每种的false表示出来
// return false;
if(!((str[i]==')'&&topElem=='(')||(str[i]==']'&&topElem=='[')||(str[i]=='}'&&topElem=='{')))
return false;
}
}
return IsEmpty(S);
}
int main()
{
char str[]="({})";
if(bracketCheck(str,4))
printf("匹配成功\n");
else
printf("匹配失败\n");
return 0;
}
typedef struct SNode *Stack;
Stack CreatStack(int MaxSize)
{
Stack S=(Stack)malloc(sizeof(struct SNode));
S->Data=(ElementType*)malloc(sizeof(ElementType)*MaxSize);
S->Top=-1;
S->MaxSize=MaxSize;
}
bool IsFull(Stack S)
{
return (S->Top==S->MaxSize-1);
}
bool Push(Stack S,ElementType X)
{
if(IsFull(S)){
printf("堆栈满\n");
return false;
}
else{
S->Data[++S->Top]=X;
return true;
}
}
bool IsEmpty(Stack S)
{
return (S->Top==-1);
}
ElementType Pop(Stack S)
{
if(IsEmpty(S)){
printf("堆栈空/n");
return false;
}
else
return S->Data[S->Top--];
}
栈在括号匹配中的应用
最新推荐文章于 2023-02-27 17:36:38 发布