stack.h
#define _CRT_SECURE_N0_WARNINGS 1
#pragma once
#define Max_size 100
#include <stdio.h>
#include <assert.h>
#include <string.h>
typedef int StackDataType;
typedef struct Stack{
StackDataType arr[Max_size];
int top;
}Stack;
//基本操作
void StackInit(Stack* pStack)
{
pStack->top = 0;
}
void StackDestroy(Stack* pStack)
{
pStack->top = 0;
}
void StackPush(Stack* pStack, StackDataType data)
{
//判断栈内是否有空间存放数据
assert(pStack->top < Max_size);
//进行压栈
pStack->arr[pStack->top++] = data;
}
void StackPop(Stack* pStack)
{
//判断栈不为空
assert(pStack->top > 0);
//进行出栈
pStack->top--;
}
StackDataType StackTop(Stack* pStack)
{
//判断栈不为空
//返回栈顶元素
return pStack->arr[pStack->top-1];
}
int StackSize(Stack* pStack)
{
return pStack->top;
}
int StackFull(Stack* pStack)
{
return pStack->top >= Max_size;
}
int StackEmpty(Stack* pStack)
{
return pStack->top <=0;
}
//-------------------------------------
void MatchBrackets(const char *arr,int size)
{
Stack stack;
StackInit(&stack);
char bracket;//字符串中的括号 等待压栈 或者与栈顶元素匹配
char leftBracket;
for (int i = 0; i < size; i++) {
bracket = arr[i];
switch (bracket) {
case '(':
case '[':
case '{':
StackPush(&stack, (StackDataType)bracket);
break;
case ')':
case ']':
case '}':
if (StackEmpty(&stack)) {
printf("右括号多\n");
StackDestroy(&stack);
return;
}
leftBracket = (char)StackTop(&stack);
StackPop(&stack);
if (leftBracket == '(' && bracket != ')') {
printf("不匹配\n");
return;
}
if (leftBracket == '[' && bracket != ']') {
printf("不匹配\n");
return;
}
if (leftBracket == '{' && bracket != '}') {
printf("不匹配\n");
return;
}
default:
break;
}
}
if (!StackEmpty(&stack)) {
printf("左括号比右括号多\n");
return;
}
printf("括号匹配\n");
}
main.c
#define _CRT_SECURE_N0_WARNINGS 1
#include "stack.h"
int main()
{
//括号匹配
const char * arr = { "(())abc{[(])}" };
const char * arr1 = { "(()))abc{[]}" };
const char * arr2 = { "(()()abc{[]}" };
const char * arr3 = { "(())abc{[]()}" };
MatchBrackets(arr, strlen(arr));
MatchBrackets(arr1, strlen(arr1));
MatchBrackets(arr2, strlen(arr2));
MatchBrackets(arr3, strlen(arr3));
return 0;
}
运行结果: