【问题描述】应用sqstack,判别表达式中圆()、方括号[ ]是否配对出现。
【样例1输入】truwe(78)i[ut(ur)]u#
【样例1输出】ok
【样例2输入】truwe(78)i[ut(ur]u)#
【样例2输出】error
【样例说明】空串输出ok。
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
#define overflow -2
#define error 0
#define ok 1
#define stack_init_size 100
#define stackincrement 10
typedef int status;
typedef int selemtype;
typedef struct
{
selemtype *base;
selemtype *top;
int stacksize;
}sqstack;
//sqstack的4个函数:
status initstack(sqstack &s) //初始化栈
{ s.base=(selemtype *)malloc(stack_init_size*sizeof(selemtype));
if (!s.base) return error;
s.top=s.base;
s.stacksize=stack_init_size;
return ok;
}
status inputstack(sqstack &s)//输入栈
{ int i,n;
//printf("please input the length of the sqstack:");
scanf("%d",&n);
//printf("please input the data of the sqstack:");
for (i=1;i<=n;i++)
{
scanf("%d",s.top);
s.top++;
}
return ok;
}
status stacktraverse(sqstack s)//输出栈,先输出长度,后输出元素
{
int i;
printf("the length of the stack:%d\n",s.top-s.base);
printf("the data of the stack:");
for (i=0;i<=s.top-s.base-1;i++)
printf("%d ",s.base[i]);
printf("\n");
return ok;
}
status destroystack(sqstack &s)//撤销栈
{
free(s.base);
s.top=NULL;
s.stacksize=0;
return ok;
}
status stackempty(sqstack s)//判空
{
if(s.top==s.base) return ok;
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;
}
status pop(sqstack &s,selemtype &e)//删除
{
if(s.top==s.base) return error;
e=*--s.top;
return ok;
}
int main()
{
selemtype e;
char ch;
sqstack s;
initstack(s);
while(ch!='#'){
ch = getchar();//getchar()函数的功能是一个一个地读取你所输入的字符。
if((ch=='[')||(ch=='('))
push(s,ch);
if((ch==']')||(ch==')')){
if(*(s.top-1)=='['&&(ch==']')||(*(s.top-1)=='(')&&(ch==')'))
pop(s,e);
}
}
if(stackempty(s))
cout<<"ok"<<endl;
else if(!stackempty(s))
cout<<"error"<<endl;
return 0;
}