0
点赞
收藏
分享

微信扫一扫

括号匹配问题

苦茶如歌 2022-02-23 阅读 90

#define _CRT_SECURE_NO_WARNINGS

#include<stdio.h>

#include <malloc.h>

#include <stdlib.h>

#include<string.h>

 

#define STACK_INIT_SIZE 100

#define STACKINCREMENT 10

 

typedef int ElemType;

typedef int Status;

 

 

 

typedef struct {

 ElemType* base;

 ElemType* top;

 int stacksize;

}SqStack;

 

Status Pop(SqStack* S);

 

void InitStack(SqStack *S) { //创建空栈

 S->base = (ElemType*)malloc(STACK_INIT_SIZE * sizeof(ElemType));

 S->top = S->base;

 S->stacksize = STACK_INIT_SIZE; //当前内存大小

}

 

void PrintStack(SqStack* S) { //输出栈中所有元素

 int e;

 while (S->top != S->base) {

  int c = Pop(S);

  printf("%d ", c);

 }

}

 

Status Pop(SqStack* S) { //用e返回栈顶元素,并且删除栈顶元素

 if (S->top == S->base) return 0;

 int e = *--S->top;

 return e;

}

 

void DeleteTop(SqStack* S) {

 S->top--;

}

 

void Push(SqStack* S, int e) { //栈顶插入元素

 if (S->top - S->base >= S->stacksize) {

  S->base = (ElemType*)realloc(S->base, (S->stacksize + STACKINCREMENT) * sizeof(ElemType));

  S->top = S->base + S->stacksize;

  S->stacksize += STACKINCREMENT;

 }

 *S->top++ = e; //相当于*S->top=e; S->top++;

}

 

Status GetTop(SqStack* S) {

 char e;

 e = *(S->top-1);

 return e;

}

 

Status isEmpty(SqStack* S) {

 if (S->top == S->base)

  return 1;

 else

  return 0;

}

 

int main() {

 int i, j;

 SqStack S;

 InitStack(&S);

 char a[100],temp;

 scanf("%s", a);

 int number = strlen(a);

 for (i = 0; i < number; i++) {

  temp = GetTop(&S);

  if ((temp == '(' && a[i] == ')') || (temp == '[' && a[i] == ']') || (temp == '{' && a[i] == '}')) {

   DeleteTop(&S);

  }

  else

  {

   Push(&S, a[i]);

  }

 }

 int c = isEmpty(&S);

 printf("%d", c);

 return 0;

}

举报

相关推荐

0 条评论