#include <stdio.h>
#define MaxSize 10
#include <string.h>
typedef struct {
char data[MaxSize];
int tap;
} SqStack;
void InitStack(SqStack s) {
s.tap = -1;
}
bool StackEmpty(SqStack s) {
if ( s.tap == -1)
return true;
else
return false;
}
bool Push(SqStack s, char x) {
if (s.tap == MaxSize - 1)
return false;
else {
s.data[++s.tap] = x;
return true;
}
}
bool pop(SqStack s, char &x) {
if (s.tap == -1)
return false;
else {
s.data[s.tap--] = x;
return true;
}
}
bool breakcheck(char str[], int length) {
SqStack s;
InitStack(s);
// a=strlen(str) = %d 用于计算数组长度
//int length = sizeof(str)/sizeof(str[0])
for (int i = 0; i < length; i++ ) {
if (str[i] == '(' || str[i] == '[' || str[i] == '{') {
Push(s, str[i]);
} else {
if (StackEmpty( s) )
return false;
char topElem;
pop(s, topElem);
if (str[i] == ')' && topElem != '(')
return false;
if (str[i] == ']' && topElem != '[')
return false;
if (str[i] == '}' && topElem != '{')
return false;
}
}
return StackEmpty(s);
}
int main(void) {
SqStack s;
int length;
char str[] = {'{', '[', ']', '}'};
int i;
length = sizeof(str) / sizeof(str[0]);
if (breakcheck(str, length))
printf("成功");
else
printf("失败");
return 0;
}
#include <stdio.h>
// 括号匹配问题
#define MaxSize 10
typedef struct {
char data[MaxSize]; // 静态数组存放栈中元素
int top; // 栈顶指针 指向数组下标,从0开始
} SqStack;
// 1、初始化
bool InitStack(SqStack &S) {
S.top = -1; // 初始化栈顶指针
return true;
}
// 2、判断栈空
bool IsEmpty(SqStack S) {
if (S.top == -1) { // 栈空
return true;
} else {
return false;
}
}
// 3、入栈
bool PushELem(SqStack &S, char e) {
if (S.top == MaxSize - 1) { // 栈满,不能插入新元素
return false;
}
S.top = S.top + 1; // 先将栈顶指针 +1
S.data[S.top] = e; // 新元素入栈
// 两行合并
// S.data[++S.top] = e 指针先加 1 ,再入栈
return true;
}
// 4、出栈
bool PopElem(SqStack &S, char &e) { // 元素出栈,并将出栈元素返回
if (S.top == -1) { // 栈空
return false;
}
e = S.data[S.top]; // 栈顶元素出栈
S.top = S.top - 1;
// e = S.data[S.top--]; 先出栈,指针 -1
return true;
}
// 5、读取栈顶元素
bool Top(SqStack S, char &e) {
if (S.top == -1) { // 栈空
return false;
}
e = S.data[S.top];
return true;
}
// 括好匹配问题
bool Cheak(char str[], int length) { // length 表示数组长度
SqStack S;
InitStack(S);
for (int i = 0; i < length ; i++) {
if (str[i] == '(' || str[i] == '[' || str[i] == '{') {
PushELem(S, str[i]); // 扫描到左括号 ,入栈
} else {
if (IsEmpty(S)) { // 扫描到右括号,但是栈为空
return false; // 匹配失败
}
char topELem;
PopElem(S, topELem); // 栈顶元素出栈,出栈元素保存在 topELem 中
if (str[i] == ')' && topELem != '(') {
return false;
}
if (str[i] == ']' && topELem != '[') {
return false;
}
if (str[i] == '}' && topELem != '{') {
return false;
}
}
}
return IsEmpty(S); // 检查完全部元素后, 栈空说名匹配成功
}
int main() {
SqStack S;
char str[] = {'{', '[', ']', '}'};
int length = sizeof(str) / sizeof(str[0]);
for (int i = 0; i < length; i++) {
printf("%c ", str[i]);
}
printf("\n\n");
if (Cheak(str, length)) {
printf("括号匹配成功!");
} else {
printf("括号匹配失败!");
}
// printf("%d",Cheak(str,length));
return 0;
}
上面的代码和下面的代码方式都是一样的但是上面的不对,望指教