修改书上的程序(片段):
#define STACK_SIZE 100
int contents[STACK_SIZE];
int top = 0;
void make_empty(void)
{
top = 0;
}
int is_empty(void)
{
return top==0;
}
int is_full(void)
{
return top==STACK_SIZE;
}
void push(int i)
{
if (is full()==STACK_SIZE)
stack_overflow();
else
contents[top++]=i;
}
int pop(void)
{
if (is_empty())
stack_underflow();
else
return contents [--top];
}
使得可以达到如下功能,要求用户输入一串圆括号或花括号,然后指出它们之间的嵌套是否正确:
Enter parenteses and/or braces:((){}{()})
parenteses and/or braces are nested properly
我对书上做了修改后如下,有三个警告,而且我觉得我的方法并不好。
#include
#define STACK_SIZE 100
char contents[STACK_SIZE];
int top = 0;
void make_empty(void)
{
top = 0;
}
int is_empty(void)
{
return top==0;
}
int is_full(void)
{
return top==STACK_SIZE;
}
void push(char i)
{
if (is_full()==STACK_SIZE)
stack_overflow();
else
contents[top++]=i;
}
char pop(void)
{
if (is_empty())
stack_underflow();
else
return contents [--top];
}
int main(void)
{
char ch;
int flag=0,flag1=0;
printf("Enter parenteses and/or braces:");
while(ch=getchar()!='\n'){
if(ch=='(' || ch=='{'){
void put(char ch);
}//压入ch进数组contents中
else if(ch==')' || ch=='}'){//如果输入是右括号的话,弹出栈顶以检测是否和输入的右括号配对
char pop(void);//弹出
if(contents[--top]=='('&&ch==')'||contents[--top]=='{'&&ch=='}')
flag=0;
else
flag++;
}
if(getchar()=='\n')
if(top==0)
flag1=0;
else
flag1++;
}
return 0;
}
警告如下:
D:\c\c\第十章程序结构\chapter10programming1.c(20) : warning C4013: 'stack_overflow' undefined; assuming extern returning int
D:\c\c\第十章程序结构\chapter10programming1.c(27) : warning C4013: 'stack_underflow' undefined; assuming extern returning int
D:\c\c\第十章程序结构\chapter10programming1.c(30) : warning C4715: 'pop' : not all control paths return a value