C语言代码,用顺序栈检查输入括号序列的匹配情况
时间: 2023-05-25 19:03:51 浏览: 109
```c
#include<stdio.h>
#include<stdlib.h>
#define STACK_INIT_SIZE 20 //栈的初始长度
#define STACK_INCREMENT 10 //栈的增量
typedef char ElemType;
typedef struct {
ElemType *base; //指向栈底的指针
ElemType *top; //指向栈顶的指针
int stacksize; //当前已分配的存储空间,以元素为单位
}SqStack;
//初始化栈
void InitStack(SqStack *S) {
S->base = (ElemType*)malloc(STACK_INIT_SIZE * sizeof(ElemType));
if (!S->base) {
exit(0);
}
S->top = S->base;
S->stacksize = STACK_INIT_SIZE;
}
//销毁栈
void DestroyStack(SqStack *S) {
free(S->base);
S->stacksize = 0;
S->top = S->base = NULL;
}
//判断栈是否为空
int StackEmpty(SqStack S) {
if (S.top == S.base) {
return 1;
}
return 0;
}
//获取栈中元素个数
int StackLength(SqStack S) {
return (S.top - S.base);
}
//获取栈顶元素
ElemType GetTop(SqStack S) {
if (S.top != S.base) {
return *(S.top - 1);
}
return ' ';
}
//入栈
void Push(SqStack *S, ElemType e) {
if (S->top - S->base >= S->stacksize) {
S->base = (ElemType*)realloc(S->base, (S->stacksize + STACK_INCREMENT) * sizeof(ElemType));
if (!S->base) {
exit(0);
}
S->top = S->base + S->stacksize;
S->stacksize += STACK_INCREMENT;
}
*(S->top) = e;
S->top++;
}
//出栈
void Pop(SqStack *S, ElemType *e) {
if (S->top == S->base) {
exit(0);
}
S->top--;
*e = *(S->top);
}
//检查输入括号序列的匹配情况
void Match(SqStack *S) {
char c;
while ((c = getchar()) != EOF) {
switch (c) {
case '(':
Push(S, c);
break;
case ')':
if (GetTop(*S) == '(') {
Pop(S, &c);
} else {
printf("Right brackets are missing!\n");
DestroyStack(S);
return;
}
break;
case '[':
Push(S, c);
break;
case ']':
if (GetTop(*S) == '[') {
Pop(S, &c);
} else {
printf("Right brackets are missing!\n");
DestroyStack(S);
return;
}
break;
case '{':
Push(S, c);
break;
case '}':
if (GetTop(*S) == '{') {
Pop(S, &c);
} else {
printf("Right brackets are missing!\n");
DestroyStack(S);
return;
}
break;
default:
break;
}
}
if (StackEmpty(*S)) {
printf("The brackets are matched!\n");
} else {
printf("Left brackets are missing!\n");
}
DestroyStack(S);
}
int main() {
SqStack S;
InitStack(&S);
printf("Please input bracket sequence:\n");
Match(&S);
return 0;
}
```
阅读全文