头文件:函数的声明
#include #include #include #include typedef char ElemType;
typedef struct node
{
ElemType data;
struct node *next;
}LStackNode,*LinkStack;
void InitStack(LinkStack *top);//将链栈初始化
int StackEmpty(LinkStack top);//判断链栈是否为空
int GetTop(LinkStack top,ElemType *e);//取栈顶元素
int PushStack(LinkStack top,ElemType e);//进栈操作
int PopStack(LinkStack top,ElemType *e);//出栈操作
int StackLength(LinkStack top);//求表长操作
void DestroyStack(LinkStack top);//销毁链表
int Match(ElemType e,ElemType ch);//判断括号
函数的定义
#include "括号配对.h"
void InitStack(LinkStack *top)//将链栈初始化
{
if((*top = (LinkStack)malloc(sizeof(LStackNode)))== NULL)
{
exit(-1);
}
(*top)->next = NULL;
}
int StackEmpty(LinkStack top)//判断链栈是否为空
{
if(top->next == NULL)
{
return 1;
}
else
{
return 0;
}
}
int GetTop(LinkStack top,ElemType *e)//取栈顶元素
{
LStackNode *p;
p = top->next ;
if(!p)
{
printf("栈已空!");
return 0;
}
*e = p->data ;
return 1;
}
int PushStack(LinkStack top,ElemType e)//进栈操作
{
LStackNode *p;
if((p = (LinkStack)malloc(sizeof(LStackNode))) == NULL)
{
printf("内存分配失败!");
return 0;
}
p->data = e;
p->next = top->next;
top->next = p;
return 1;
}
int PopStack(LinkStack top,ElemType *e)//出栈操作
{
LStackNode *p;
p = top->next ;
if(!p)
{
printf("栈已空!");
return 0;
}
top->next = p->next ;
*e = p->data ;
free(p);
return 1;
}
int StackLength(LinkStack top)//求表长操作
{
LStackNode *p;
int count = 0;
p = top;
while(p->next != NULL)
{
p = p->next ;
count++;
}
return count;
}
void DestroyStack(LinkStack top)//销毁链表
{
LStackNode *p,*q;
p = top;
while(!p)
{
q = p;
p = p->next ;
free(q);
}
}
int Match(ElemType e,ElemType ch)
{
if(e == '('&&ch == ')')
{
return 1;
}
else if(e == '['&&ch == ']')
{
return 1;
}
else if(e == '{'&&ch == '}')
{
return 1;
}
else
{
return 0;
}
}
函数的应用
#include "括号配对.h"
int main(void)
{
LinkStack S;
char *p;
ElemType e;
ElemType ch[60];
InitStack(&S);
printf("请输入其请输入带括号的表达式('()','[]','{}').\n");
gets(ch);
p = ch;
while(*p)
{
switch(*p)
{
case '(':
case '[':
case '{':
PushStack(S,*p++);
break;
case ')':
case ']':
case '}':
if(StackEmpty(S))
{
printf("缺少左括号.\n");
return 0;
}
else
{
GetTop(S,&e);
if(Match(e,*p))
{
PopStack(S,&e);
}
else
{
printf("左右括号不匹配!\n");
return 0;
}
}
default:
p++;
}
}
if(StackEmpty(S))
{
printf("括号匹配!\n");
}
else
{
printf("缺少右括号!\n");
}
return 0;
}