堆栈做了个检验括号是否匹配的程序,不知错哪 。 求指点错在哪里
// 括号匹配.cpp : Defines the entry point for the console application.//用堆栈的方式实现括号的配对问题
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 100 //存储空间初始分量为100
#define STACKINCREMENT 10 //存储空间分配增量为10
#define OVERFLOW -2
#define OK 1
#define ERROR 0
typedef struct stack
{
char *base;
char *top;
int stacksize;
}SqStack;
char InitStack(SqStack &s);
char GetTop(SqStack s,char &e);
char Push(SqStack &s,char e);
char Pop(SqStack &s,char &e);
char InitStack(SqStack &s) //构造空栈
{
s.base = (char *)malloc(STACK_INIT_SIZE * sizeof(char));
if(!s.base) exit (OVERFLOW);
s.top = s.base;
s.stacksize = STACK_INIT_SIZE;
return OK;
}
char GetTop(SqStack s,char &e) //判定栈是否为空,若空报错
{
if(s.top == s.base) return ERROR;
e = *(s.top-1);
return OK;
}
char Push(SqStack &s,char e) //压栈
{
if(s.top -s.base >= s.stacksize) // 栈满,加空间
{
s.base = (char *)realloc(s.base,(s.stacksize +STACKINCREMENT) * sizeof(char));
if(!s.base) exit (OVERFLOW); //存储分配失败
s.top = s.base+s.stacksize;
s.stacksize += STACKINCREMENT;
}
*s.top++ = e;
return OK;
}
char Pop(SqStack &s,char &e) //出栈
{
if(s.top =s.base) return ERROR;
e = * --s.top;
return OK;
}
bool BracketsCorrespondency(SqStack &s)
{
char a[STACK_INIT_SIZE];
int i=0;
InitStack(s);
char x;
printf("请输入带括号字符串:\n");
scanf("%s",a);
while(a[i])
{
switch(a[i])
{
case '(' : Push(s,a[i]); break;
case '[' : Push(s,a[i]); break;
case ')' : GetTop(s,x);
if (x=='(') Pop(s,x);
else return ERROR;break;
case ']' : GetTop(s,x);
if (x=='[') Pop(s,x);
else return ERROR;break;
default:break ;
}
i++;
}
if(s.stacksize !=0) return ERROR;
return OK;
}
int main()
{
SqStack s;
InitStack(s);
if(BracketsCorrespondency(s))
printf("括号匹配\n");
else
printf("括号不匹配!\n");
return 0;
}
[ 本帖最后由 进击的蛋炒饭 于 2014-5-14 00:17 编辑 ]