栈的应用-括号的匹配

//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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值