#include "myhead.h"
//栈
struct stack
{
char data;
struct stack *next;
};
//初始化
struct stack *init()
{
struct stack *p=malloc(sizeof(struct stack));
p->next=NULL;
return p;
}
//入栈
int push(struct stack *p,int n)
{
struct stack *new=malloc(sizeof(struct stack));
new->data=n;
new->next=p->next;
p->next=new;
}
//出栈
char pop(struct stack *p)
{
struct stack *q=p->next;
char n;
if(p->next==NULL)
return -1;
n=p->next->data;
p->next=p->next->next;
free(q);
return n;
}
int main()
{
int i=0;
char temp;
char buf[200]="shfhd(hdfhfhdh) fdjfjdjfj} [fhdhsfhdsh (fdhsfh)";
struct stack *filo=init();//栈初始化
while(buf[i]!='\0')
{
if(buf[i]=='(' || buf[i]=='{' || buf[i]=='[')//入栈
{
push(filo,buf[i]);
printf("%c 进栈!\n",buf[i]);
}
if(buf[i]==')' || buf[i]=='}' || buf[i]==']')//出栈
{
temp=pop(filo);
if(temp==-1)//栈内没有东西
printf("没有东西可以出栈了!\n");
else
printf("%c 出栈!\n",temp);
//判断3种括号是否匹配
if('('!=temp && buf[i]==')')
printf("%c 与前面不匹配!\n",buf[i]);
if('['!=temp && buf[i]==']')
printf("%c 与前面不匹配!\n",buf[i]);
if('{'!=temp && buf[i]=='}')
printf("%c 与前面不匹配!\n",buf[i]);
}
i++;//下一个字符
}
while(NULL!=filo->next)//全部出栈
{
printf("%c 后缺少与其匹配的字符!\n",pop(filo));
}
return 0;
}