括号匹配,数据结构栈
#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define STACK_INIT_SIZE 100
typedef char SElemType;
typedef int status;
typedef struct
{
SElemType *top;
SElemType *base;
status stacksize;
}SqStack;
status InitStack(SqStack &s)
{
s.base=(SElemType*)malloc(STACK_INIT_SIZE*sizeof(SElemType));
if(!s.base)return ERROR;
s.base=s.top;
s.stacksize=STACK_INIT_SIZE;
return OK;
}
status push(SqStack &s,SElemType i)
{
if((s.top-s.base)>=s.stacksize)return ERROR;
*s.top=i;
s.top++;
}
status pop(SqStack &s,SElemType &i)
{
if(s.top==s.base)return ERROR;
i=*s.top;
s.top--;
return OK;
}
main()
{
SqStack s;
SElemType e;
while((s.top-s.base)<=s.stacksize)
{
scanf("%c",&e);
if(e=='['||e=='(')
push(s,e);
if(e==')')
{
if(*s.top--=='(')
pop(s,*s.top);
else
{
printf("ERROR!");exit(0);
}
}
if(e==']')
{
if(*s.top--=='[')
pop(s,*s.top);
else
{
printf("ERROR!");exit(0);
}
}
s.top++;
}
printf("OK!\n");
}
不知道哪里错了,求指教
[解决办法]
严伟明教材应该有吧
感觉没有必要用栈,直接扫描
呵呵,
[解决办法]
status pop(SqStack &s,SElemType &i)
{
if(s.top==s.base)return ERROR;
i=*s.top;//
s.top--;//这两个语句换一下位置就对了。
return OK;
}
弹栈这里出问题了。