#include
#include
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;
typedef char SElemType;
typedef struct
{
SElemType base;
SElemType *top;
int stacksize;
}SqStack;
Status InitStack(SqStack *S)
{
S->base=(SElemType *)malloc(STACK_INIT_SIZE*sizeof(SElemType));
S->top=S->base;
S->stacksize=STACK_INIT_SIZE;
return OK;
}
Status StackEmpty(SqStack *S) //判斷棧是否為空,若為空返回TURE,否返回FALSE
{
if(S->top!=S->base) return ERROR;
return OK;
}
Status Push(SqStack *S,SElemType e) //插入元素e為新棧頂元素
{
if(S->top-S->base>=S->stacksize) //棧滿追加空間
{
S->base=(SElemType)realloc(S->base,(S->stacksize+STACKINCREMENT)*sizeof(SElemType));
if (!S->base) exit(OVERFLOW); //存儲分配失敗
S->top=S->base+S->stacksize;
S->stacksize+=STACKINCREMENT;
}
S->top++=e;
return OK;
}
Status GetTop(SqStack *S,SElemType *e) //棧不空用e返回棧頂元素,並返回OK 否則返回ERROR
{
if(S->top==S->base) return ERROR;
*e=(S->top-1);
return OK;
}
Status Pop(SqStack S,SElemType*e) //棧不空刪除S棧頂元素,用e返回其值,並返回OK,否則返回ERROR
{
if(S->top==S->base) return ERROR;
*e=--S->top;
return OK;
}
Status Bracket(SqStack *S,char *str) //檢測括號匹配
{
int i=0,flag1=0,flag2;
SElemType e;
while(str[i]!='\0')
{
switch(str[i])
{
case '(':{Push(S,'(');break;}//入棧
case '[':{Push(S,'[');break;}
case '{':{Push(S,'{');break;}
case ')':{ if(GetTop(S,&e)=='(') //是否與棧頂元素相等
Pop(S,&e); //出棧
else
flag1=1;
break;
}
case ']':{ if(GetTop(S,&e)=='[')
Pop(S,&e);
else
flag1=1;
break;
}
case '}':{ if(GetTop(S,&e)=='{')
Pop(S,&e);
else
flag1=1;
break;
}
default: break;
}
if(flag1) break;
i++;
}
flag2=StackEmpty(S); //棧是否為空並將返回值值賦給flag2
if(!flag1 && flag2) printf("括號匹配正確!\n");
else printf("括號匹配失敗!\n");
return OK;
}
int main()
{
char a,flag='y';
while(flag=='y')
{
char str[255];
SqStack S;
InitStack(&S);
printf("請輸入帶括號的表達式:\n");
scanf("%s",str);
scanf("%c",&a);
Bracket(&S,str);
printf("是否要再次輸入?(Enter y again):\n ");
scanf("%c",&flag);
printf("\n");
}
printf("close.\n");
}
我已經自己弄明白了。哈哈哈