#include <stdio.h>
#include <malloc.h>
#include<stdlib.h>
#define MAXSIZE 300
typedef char datatype;
typedef struct //定義順序棧的結構儲存
{
datatype data[MAXSIZE];
int top;
}SeqStack;
//初始化順序棧
SeqStack *InitStack()
{
SeqStack *s;
s=(SeqStack *)malloc(sizeof(SeqStack));//開闢棧的儲存空間
s->top=-1;
return s;
}
SeqStack *Push(SeqStack *s,datatype x) //入棧
{
if(s->top==MAXSIZE-1)//判斷棧是否滿
{
printf("The stack is overflow!/n");
return NULL;
}
else
{
s->top++; //棧頂加 1,元素入棧
s->data[s->top]=x;
return s;
}
}
datatype Pop(SeqStack *s) //出棧
{
if(s->top==-1)//判斷棧是否為空白
{
printf("The stack is empty!/n");
return false;
}
else
{
s->top--;
return s->data[s->top+1];
}
}
datatype GetTop(SeqStack *s) //取出棧頂
{
if(s->top==-1) //判斷棧是否為空白
{
printf("The stack is empty!/n");
return false;
}
else
{
return s->data[s->top];
}
}
bool StackEmpty(SeqStack *s) //判斷是否是空棧
{
if(s->top==-1)
return true;
else
return false;
}
SeqStack *ClearStack(SeqStack *s) //清除棧
{
if(s!=NULL)
{
free(s);//釋放棧中所有元素 直到 s==NULL
printf("棧空間釋放完畢!/n");
s=NULL;
return s;
}
else
{
printf("棧為空白!/n");
return s;
}
}
//括弧匹配函數
bool match(SeqStack *s,char c[])
{
int i=0;
while(c[i]!='/0')
{
switch(c[i])
{
case '{':
case '[':
case '(': Push(s,c[i]);
break;
case ')':
if(!StackEmpty(s) && GetTop(s)=='(')
{
Pop(s);
break;
}
else
return false;
case ']':
if(!StackEmpty(s) && GetTop(s)=='[')
{
Pop(s);
break;
}
else
return false;
case '}':
if(!StackEmpty(s) && GetTop(s)=='{')
{
Pop(s);
break;
}
else
return false;
}
i++;
}
return (StackEmpty(s));
}
int main()
{
SeqStack *s;
int t,i;
char str[300];
int ch;
do{
printf("/n歡迎使用括弧配對程式:/n");
printf("=======================/n");
printf("1 進入/n");
printf("0 退出/n");
printf("=======================/n");
printf("請輸入你的選擇:");
scanf("%d",&t);
if(t!=1&&t!=0)
{
printf("/n你的輸入無效!/n");
continue;
}
switch(t)
{
case 1:
printf("/n請輸入要驗證的括弧序列:/n");
scanf("%s",str); //輸入要驗證的括弧序列
s=InitStack();
if(match(s,str))
{
printf("你輸入括弧匹配!/n");
}
else
{
printf("你輸入括弧不匹配!/n");
}
printf("/n");
break;
case 0:
printf("謝謝使用括弧配對程式!/n");
printf("下次再見!/n/n");
}
s=ClearStack(s); //清除棧 在檢驗完畢後
printf("************************/n");
printf(" ^ ^ /n"); //每次檢驗完畢後顯示新穎畫面,美觀!!
printf(" = /n");
} while(t!=0);
return 0;
}