C語言資料結構如何判斷表示式是否匹配
#include<cstring>
#include<malloc.h>
using namespace std;
#define MAXSIZE 100
typedef int datatype;
typedef struct
{
datatype a[MAXSIZE];
int top;
}sequence_stack;
//棧(順序儲存)初始化
void init(sequence_stack *st)
{
st->top = 0;
}
//判斷棧是否為空
int empty(sequence_stack st)
{
return(st.top ? 0 : 1);
}
//取得棧頂的結點值
datatype read(sequence_stack st)
{
if (empty(st))
{
printf("\n棧是空的!");
exit(1);
}
else
return st.a[st.top -1];
}
//棧的插入操作
void push(sequence_stack *st,datatype x)
{
if(st ->top == MAXSIZE)
{
printf("\n The sequence stack is full!");
exit(1);
}
st -> a[st -> top] = x;
st -> top ++;
}
//棧的刪除操作
void pop(sequence_stack *st)
{
if(st -> top == 0)
{
printf("\nThe sequence stack is empty!");
exit(1);
}
st -> top--;
}
//判斷表示式括號是否匹配
int match_kuohao(char c[])
{
int i = 0;
sequence_stack s;
init(&s);
while(c[i] != '#')
{
switch(c[i])
{
case '{':
case '[':
case '(':push (&s,c[i]);
break;
case '}':if(!empty(s) && read(s) == '{')
{
pop(&s);
break;
}
else return 0;
case ']':if(!empty(s) && read(s) == '[')
{
pop(&s);
break;
}
case ')':if(!empty(s) && read(s) == '(')
{
pop(&s);
break;
}
else return 0;
}
i ++;
}
return (empty(s));
}
int main()
{
char s[100];
cout<<"請輸入一個長度小於100的字串:"<<endl;
cin>>s;
int re = match_kuohao(s);
if(re == 0)
{
cout<<"你輸入的字串括號匹配!"<<endl;
}
else if (re == 11)
{
cout<<"你輸入的字串括號不匹配!"<<endl;
}
return 0;
}