//STACK.H
#ifndef STACK_H
#define STACK_H#include <stdlib.h>
#define STACK_INIT_SIZE 100 //存储空间初始分配量
#define STACKINCREMENT 10 //存储空间分配增量
#define SElemType char
#define Status int
typedef struct{
SElemType *top;
SElemType *base;
int stacksize;
}SqStack;
Status InitStack(SqStack *S);
Status Push(SqStack *S, SElemType e);
Status Pop(SqStack *S, SElemType *e);
Status StackEmpty(SqStack S);
Status GetTop(SqStack S, SElemType *e);
Status InitStack(SqStack *S)
{
S->base = (SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType));
if(!S->base)
exit(0);
S->top = S->base;
S->stacksize = STACK_INIT_SIZE;
return 0;
}
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(0);
S->top = S->base + S->stacksize;
S->stacksize += STACKINCREMENT;
}
*S->top++ = e;
return 0;
}
Status Pop(SqStack *S, SElemType *e)
{
if(S->top == S->base) //栈空
exit(0);
*e = *--S->top;
return 0;
}
Status StackEmpty(SqStack S)
{
if(0 == S.top -S.base)
return 1; //堆栈为空
return 0;
}
Status GetTop(SqStack S, SElemType *e)
{
if(0 == S.top - S.base)
return 1;
*e = *(S.top - 1);
return 0;
}
#endif
#include "STACK.H"
#include <stdio.h>
//main.c
int main ()
{
char ch1;
char ch2 = 0;
int n = 0;
SqStack S;
InitStack(&S);
while(ch1 = getchar())
{
switch(ch1)
{
case '(':
case '[':
case '{':
Push(&S, ch1);
continue;
case ' ':
case '\t':
case '\n':
continue; //取走缓冲区的空白字符
case ')':
if(!StackEmpty(S)){
if('(' == (GetTop(S,&ch2),ch2)){
Pop(&S, &ch2);
printf("%c %c\n",ch2, ch1);
continue;
}
printf("不合法\n");
break;
}
case ']':
if(!StackEmpty(S)){
if('[' == (GetTop(S,&ch2),ch2)){
Pop(&S, &ch2);
printf("%c %c\n",ch2, ch1);
continue;
}
printf("不合法\n");
break;
}
case '}':
if(!StackEmpty(S)){
if('{' == (GetTop(S,&ch2),ch2)){
Pop(&S, &ch2);
printf("%c %c\n",ch2, ch1);
continue;
}
printf("不合法\n");
break;
}
case '#':
printf("输入结束\n");
break; //跳出switch语句
default: //取走缓冲区中不合法的字符
continue;
}
break; //结束循环
}
return 0;
}