您的位置:首页 > 理论基础 > 数据结构算法

数据结构 栈应用(括号匹配检测)

2012-05-01 16:47 573 查看
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define OK    1
#define ERROR 0
#define STACK_INIT_SIZE 10
#define STACKINCREMENT   2

typedef int  Status;
typedef char SElemType;

typedef struct SqStack
{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;

Status InitStack(SqStack *S)
{
(*S).base = (SElemType *)malloc(STACK_INIT_SIZE*sizeof(SElemType));
if (!(*S).base)
exit(OVERFLOW);
(*S).top = (*S).base;
(*S).stacksize = STACK_INIT_SIZE;
return OK;
}

Status StackEmpty(SqStack S)
{
if (S.base == S.top)
return OK;
else
return ERROR;
}

Status Push(SqStack *S,SElemType e)
{
if ((*S).top - (*S).base >= (*S).stacksize)
{
(*S).base = (SElemType *)realloc((*S).base,((*S).stacksize + STACKINCREMENT)*sizeof(SElemType));
if (!(*S).base)
exit(OVERFLOW);
(*S).top = (*S).base + (*S).stacksize;
(*S).stacksize +=STACKINCREMENT;
}
*((*S).top)++ = e;
return OK;
}

Status Pop(SqStack *S,SElemType *e)
{
if ((*S).base == (*S).top)
return ERROR;
*e = *--(*S).top;
return OK;
}

void main()
{
SqStack S;
SElemType ch[100],*p,e;
if(InitStack(&S))
{

printf("请输入表达式\n");
gets(ch);
p = ch;
while (*p)
switch(*p)
{
case '(':
case '[':Push(&S,*p++);
break;
case ')':
case ']':if(!StackEmpty(S))
{
Pop(&S,&e);
if(*p == ')' && e != '(' || *p == '[' && e != ']')
{
printf("左右括号不配对");
exit(OVERFLOW);
}
else
{
p++;
break;
}
}
else
{
printf("缺乏左括号!\n");
exit(ERROR);
}
default : p++;
}
if(StackEmpty(S))
printf("左右括号匹配!\n");
else
printf("缺少右括号!\n");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: