C语言用栈的数据结构判断括号是否匹配
栈的结构体及栈的基本操作
(栈的代码我写在名为”SqStack.h"的头文件里)
#pragma once
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 10
//结构体
typedef struct SqStack {
char data[MAXSIZE];
int top;
}SqStack;
//创建
bool initSqStack(SqStack*& S) {
S = (SqStack*)malloc(sizeof(SqStack));
if (S == NULL)
return false;
S->top = -1;
}
//消除
void destoryStack(SqStack*& S) {
free(S);
}
//判空
bool isEmpty(SqStack* S) {
if (S->top == -1) {
return true;
} else {
return false;
}
}
//判满
bool isFull(SqStack* S) {
if (S->top == MAXSIZE - 1)
return true;
else
return false;
}
//入栈
bool push(SqStack*& S, char e) {
if (isFull(S)) {
return false;
}
S->top++;
S->data[S->top] = e;
return true;
}
//出战
bool pop(SqStack*& S, char& e) {
if (isEmpty(S)) {
return false;
}
e = S->data[S->top];
S->top--;
return true;
}
//获得栈顶元素
bool getTop(SqStack* S, char& e) {
if (S == NULL) {
return false;
}
e = S->data[S->top];
}
//遍历
bool printStack(SqStack* S) {
if (S == NULL) {
return false;
}
for (int i = 0; i < S->top; i++) {
printf("%c",S->data[i]);
}
printf("%c\n", S->data[S->top]);
return true;
}
//获取长度
int getLength(SqStack* S) {
return S->top++;
}
//以默认值初始化顺序栈
SqStack* createSqStack(int length) {
SqStack* S;
initSqStack(S);
for (int i = 0; i < length; i++) {
push(S, i);
}
return S;
}
判断括号是否匹配
(代码写在“bracketMatching.h"的头文件里)
1.判断逻辑
2.代码
#pragma once
#include"SqStack.h"
//判断字符串的长度
int length(char str[]) {
if (str == NULL) {
printf("字符串为空\n");
return -1;
}
int i = 0;
while (str[i] != NULL) {
i++;
}
return i;
}
//判断左右符号类型是否匹配
bool isTypeMatched(char src, char target) {
switch (src) {
case ')':
if (target == '(') {
return true;
}else {
printf("%c前是%c,不匹配\n", src, target);
return false;
}
break;
case '}':
if (target == '{') {
return true;
} else {
printf("%c前是%c,不匹配\n", src, target);
return false;
}
break;
case ']':
if (target == '[') {
return true;
} else {
printf("%c前是%c,不匹配\n", src, target);
return false;
}
break;
default:
return false;
break;
}
}
//判断字符串是否匹配括号
bool isMatched(char str[]) {
if (str == NULL) {
printf("字符串为空\n");
return false;
}
SqStack* s;
initSqStack(s);
for (int i = 0; i < length(str); i++) {
char topElem;
switch (str[i]) {
case '(':
case '[':
case '{':
push(s, str[i]);
break;
case ')':
case '}':
case ']':
if (pop(s,topElem)){
if (isTypeMatched(str[i], topElem)) {
} else {
return false;
}
} else {
printf("%c前无元素\n", str[i]);
return false;
}
default:
break;
}
}
if (isEmpty(s)) {
return true;
} else {
printf("栈空,左括号不匹配\n");
return false;
}
}
测试
#include"bracketMatching.h"
void main() {
char str[] ="()((()))";
if (isMatched(str))
printf("匹配");
}
下面是项目目录