C语言程序设计:现代方法 P170 第一题:
当读入左括号或者左花括号时,把它们像字符一样压入栈中,当读入右圆括号或右花括号时,把栈顶的项弹出,并且检查弹出的项是否为匹配的圆括号或者花括号。
# define _CRT_SECURE_NO_WARNINGS
# include<stdio.h>
# include<stdlib.h>
# include<stdbool.h>
#define N 20
char content[N];
int top = 0;
void make_empty(void);
bool is_empty(void);
bool is_full(void);
void push(char i);
char pop(void);
int main(void){
char ch;
bool bad;
printf("enter parenteses or braces:");
while ((ch = getchar()) != '\n'){
switch (ch){
case '(':
case '{':
push(ch); break;
case ')':
if (pop() != 41)
{
bad = true;
}
break;
case'}':
if (pop() != 123)
{
bad = true;
}
break;
default: bad = true;
break;
}
}
if (is_empty())
printf("paratest are nested properly.");
else if (bad)
printf("paratest are not nested properly.");
system("pause");
return 0;
}
void push(char ch){
if (is_full())
stack_overflow();
content[top++] = ch;
}
char pop(void){
if (is_empty())
stack_underflow();
return content[--top];
}
bool is_empty(void){
return (top == 0);
}
bool is_full(void){
return top == N;
}