//使用堆疊進行括號匹配
#include <stdio.h>
#include <malloc.h>
#define MaxSize 10
typedef struct{
char data[MaxSize];
int top;
}SqStack;
void InitStack(SqStack *); //初始化
int StackEmpty(SqStack); //判斷堆疊是否為空
void Push(SqStack * , char); //入堆疊
char Pop(SqStack * , char *); //出堆疊
int BracketCheck(char [] , int); //括號檢查
int main(void){
char str[] = "((([{}}])))";
int length = strlen(str);
if(BracketCheck(str , length)){
printf("括號成對!");
}else{
printf("括號不成對!");
}
return 0;
}
//初始化
void InitStack(SqStack *S){
S->top = -1;
}
//判斷堆疊是否為空
int StackEmpty(SqStack S){
if(S.top == -1){
return 1;
}
return 0;
}
//入堆疊
void Push(SqStack *S , char c){
if(S->top == MaxSize - 1){
printf("堆疊滿!\n");
return;
}else{
S->data[++S->top] = c;
}
}
//出堆疊
char Pop(SqStack *S , char *e){
if(StackEmpty(*S)){
printf("堆疊為空!\n");
}else{
(*e) = S->data[(S->top)--];
}
return (*e);
}
//括號檢查
int BracketCheck(char str[] , int len){
SqStack S;
InitStack(&S);
int i;
for(i = 0 ; i < len ; i ++){
if(str[i] == '(' || str[i] == '[' || str[i] == '{'){
Push(&S , str[i]);
}else{
if(StackEmpty(S)){
return 0;
}else{
char topElem;
Pop(&S , &topElem);
if(str[i] == ')' && topElem != '('){
return 0;
}
if(str[i] == ']' && topElem != '['){
return 0;
}
if(str[i] == '}' && topElem != '{'){
return 0;
}
}
}
}
return StackEmpty(S);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/75823.html
標籤:其他
上一篇:案例6-1.3 哥尼斯堡的“七橋問題” (25分)---C語言
下一篇:如何通過刷題提高演算法能力
