#include<stdio.h>
#include<stdlib.h>
//用可动态分配的一维数组实现栈
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define OK 0
#define ERROR 1
typedef char SElemType;//类型更改为char
typedef bool Status;
typedef struct
{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
// init stack
Status InitStack(SqStack &S)
{
S.base = (SElemType *)malloc(sizeof(SElemType)*STACK_INIT_SIZE);
if (!S.base) return ERROR;
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
return OK;
}
Status DestroyStack(SqStack &S)
{
free (S.base);
S.base = S.top = NULL;
S.stacksize = 0;
return OK;
}
Status ClearStack(SqStack &S)
{
S.base = S.top = NULL;
S.stacksize = 0;
return OK;
}
Status StackEmpty(SqStack &S)
{
return S.top == S.base;
}
Status StackLengh(SqStack &S)
{
//return (S.top - S.base)/sizeof(SElemType);
return S.top - S.base;
}
//push
Status StackPush(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) return ERROR;
S.top = S.base + S.stacksize;
S.stacksize += STACKINCREMENT;
}
*S.top++ = e;
return OK;
}
//by zhaoyang 2014.4.16
//pop
Status StackPop(SqStack &S,SElemType &e)
{
if (S.base == S.top) return ERROR;
e = *--S.top;
return OK;
}
//by zhaoyang 2014.4.16
bool compare(char a, char b)
{
if (a == '(' && b ==')' ) return true;
if (a == '[' && b ==']' ) return true;
if (a == '{' && b =='}' ) return true;
return false;
}
int main()//基于顺序栈的 括号匹配检测 (){}[]
{
SqStack A;
char ch;
char t;
InitStack(A);
ch=getchar();
int flag = 0;
while (ch != '\n')
{
if (ch == '(' || ch == '{' || ch == '[') StackPush(A,ch);
else if (ch == ')' || ch == '}' || ch == ']')
{
StackPop(A, t);
if (!compare(t, ch))
{
flag = 1;
break;
}
}
ch = getchar();
}
if (flag) printf("\n括号匹配出错");
else printf("匹配正确");
return 0;
}
5.基于顺序栈 实现 检测括号匹配程序
最新推荐文章于 2022-01-20 15:35:15 发布