#include<stdio.h>
#include<malloc.h>
#include<string.h>
#define ElemType char
#define MAXSIZE 1000
typedef struct LinkStack
{//定义链栈结构 ,其实质是一个受限的单链表
ElemType data;
struct LinkStack *next;
}LinkStack;
LinkStack *Init(LinkStack *top)
{
//初始化一个带有头结点的链栈 top=(LinkStack *)malloc(sizeof(LinkStack));
top->next=NULL; return top;
}
LinkStack *Push(LinkStack *top,ElemType &e)
{//入栈操作 LinkStack *p; p=(LinkStack *)malloc(sizeof(LinkStack));
if(p==NULL){ printf("栈满"); }
else{ p->data=e; p->next=top->next; top->next=p; }
return top;
}
char Pop(LinkStack *top){//此块可用于括号匹配的出栈操作 //八进制算法的出栈操作只需修改函数返回的值类型即可
LinkStack *p; ElemType e;
p=top->next; if(p==NULL){ printf("栈空"); } else{ e=p->data; top->next=p->next; free(p); }
return e;
}
void Get(LinkStack *top){//获取栈顶元素,元素仍在栈内 ElemType e; LinkStack *p; p=top->next; if(p==NULL){ printf("空栈"); }else{ printf(" 取栈顶元素:");
e=p->data; printf("%d ",e);
}
}
void equal(LinkStack *top,char *s){//括号匹配算法
char ch;
top=Init(top);//初始化一个带头结点的链栈
while(*s){ if(*s=='['||*s=='('){ Push(top,*s); }
if(*s==')'){ ch=Pop(top);
if(ch!='('){ printf("括号匹配失败"); break; }
}
if(*s==']'){ ch=Pop(top);
if(ch!='['){ printf("括号匹配失败");
break; }
} s++;
}
if(*s==NULL){ printf("括号匹配全部成功"); }
}
/*void Coversion(ElemType dec){//十进制转换成八进制 ElemType e; LinkStack *top,*p; top=Init(top);
for(;dec!=0;dec=dec/8){ e=dec%8; top=Push(top,e); }
for(p=top->next;p;p=top->next){ top=Pop(top); }
} */
int main(){
LinkStack *top;
//ElemType dec;
ElemType *s;
ElemType arr[MAXSIZE];
/*此块是十进制转换成八进制的代码 printf("输入十进制数: ");
scanf("%d",&dec); printf("对应的八进制是:");
Coversion(dec); */ //以下是括号匹配的代码 printf("输入一个字符串:");
gets(arr);
s=arr;
equal(top,s);
return 0;
}