<span style="font-size:24px;">copy from:<a target=_blank href="http://blog.chinaunix.net/uid-25502868-id-167703.html">http://blog.chinaunix.net/uid-25502868-id-167703.html</a></span>
/*
Check if parenthesis ( ), brackets [ ], and braces { } are balanced.
栈的应用————平衡符号
by gongzh
2011.3.12
*/
/*
算法思想:
Algorithm{
Make an empty stack;
while(read in a character ch)
{
if( ch is a open symbol)
push(c,S);
else if(ch is a close symbol)
{
if(IsEmpty){error;exit;}
else
{
if(Top(S) is not match ){error,exit;}
else pop(S);
}
}
}//end whlile-loop
if(emis not empty){error;exit;}
}
*/
#include <stdio.h>
#include <stdlib.h>
#define Error(Str) fprintf(stderr,"%s\n",Str),exit(1)
struct Node{
char elem;
struct Node *next;
};//栈的链表实现
typedef struct Node *Stack;
int CheckSymbol(Stack S);//检测平衡符号的函数
Stack CreateStack(void);/*创建一个空栈*/
void MakeEmpty(Stack);
int IsEmpty(Stack);//测试栈是否是空栈
void Push(char ,Stack);//入栈
void Pop(Stack);//出栈
char Top(Stack);//获取栈顶元素
void DisposeStack(Stack);//销毁栈
int main()
{
Stack S;
S=CreateStack();
if(CheckSymbol(S))
printf("wrong\n");
else
printf("right\n");
DisposeStack(S);
return 0;
}
int CheckSymbol(Stack S)
{
char ch;
printf("input characters as {,} or (,)or [,] \n");
printf("and # to quit\n");
while((ch=getchar())!='#')//输入平衡字符
{
if(ch=='{'||ch=='['||ch=='(') /*开放符号*/
Push(ch,S);
else if(ch=='}'||ch==']'||ch==')') /*封闭符号*/
{
if(IsEmpty(S)) /*栈里无字符*/
Error("stack is empty.");
else
{
switch(ch)
{
case '}':
if(Top(S)!='{')//不匹配
Error("not match");
else
break;//匹配成功
case ')':if(Top(S)!='(')
Error("not match");
else
break;
case ']':if(Top(S)!='[')
Error("not match");
else break;
}
/*匹配成功,将栈中匹配成功的符号弹出*/
Pop(S);
}
}
}
if(!IsEmpty(S))//如果最后栈里还有字符,则说明未匹配完,即出错
Error("the stack is not empty last");
else
return 0;//成功
}
/*栈的基本操作——链表实现*/
Stack CreateStack(void)
{
Stack S;
S=malloc(sizeof(struct Node));
if(S==NULL)
Error("out of space");
S->next=NULL;
MakeEmpty(S);
return S;
}
void MakeEmpty(Stack S)
{
if(S==NULL) //未创建栈
Error("must usr CreateStack first");
else
while(!IsEmpty)
Pos(S);
}
int IsEmpty(Stack S)
{
return S->next==NULL;
}
void Push(char ch,Stack S)
{
Stack tmp;
tmp=malloc(sizeof(struct Node));
if(!tmp)
Error("out of space");
tmp->elem=ch;
tmp->next=S->next;
S->next=tmp;
}
void Pop(Stack S)
{
Stack tmp;
if(IsEmpty(S))
Error("empty stack");
else
{
tmp=S->next;
S->next=tmp->next;
free(tmp);
}
}
char Top(Stack S)
{
if(!IsEmpty(S))
return S->next->elem;
Error("empty stack.");
return 0;
}
void DisposeStack(Stack S)
{
if(S==NULL)
Error("no stack");
MakeEmpty(S);
free(S);
}