icoding 实验四 栈
#include
#include
#include
#define STACK_SIZE 100
char contents[STACK_SIZE];
int top = 0;
void stack_overflow(void)
{
printf(“Stack overflown”);
exit(EXIT_FAILURE);
}
void stack_underflow(void)
{
printf(“Stack underflown”);
exit(EXIT_FAILURE);
}
void make_empty(void)
{
top = 0;
}
bool is_empty(void)
{
return top == 0;
}
bool is_full(void)
{
return top == STACK_SIZE;
}
void push(char ch)
{
if (is_full())
stack_overflow();
else
contents[top++] = ch;
}
char pop(void)
{
if (is_empty())
stack_underflow();
else
return contents[–top];
return ‘’;
}
int main(void)
{
char ch,elem;
printf(“Enter parentheses and/or braces:”);
while((ch=getchar())!=’n’){
if(ch==’(’||ch==’{’){
push(ch);//左右括号入栈
}
else if(ch==’)’||ch==’}’){
if(!is_empty()){
elem=pop();//出栈赋值
if(elem==’(’&&ch==’)’){
continue;
}
else if(ch==’}’&&elem==’{’){
continue;
}
else{
printf(“Parentheses/braces are NOT nested properly”);
break;
}
}
else{
printf(“Parentheses/braces are NOT nested properly”);
break;
}
}
}
if(is_empty()){
printf(“Parentheses/braces are nested properly”);
}
else{
printf(“Parentheses/braces are NOT nested properly”);
}
return 0;
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)