您好,登錄后才能下訂單哦!
在C語言中,我們可以使用棧數據結構來實現括號匹配檢查
#include<stdio.h>
#include <stdlib.h>
#include<string.h>
typedef struct Stack {
char *data;
int top;
int size;
} Stack;
Stack *createStack(int size) {
Stack *stack = (Stack *)malloc(sizeof(Stack));
stack->data = (char *)malloc(size * sizeof(char));
stack->top = -1;
stack->size = size;
return stack;
}
void push(Stack *stack, char value) {
if (stack->top == stack->size - 1) {
printf("Stack is full\n");
return;
}
stack->data[++stack->top] = value;
}
char pop(Stack *stack) {
if (stack->top == -1) {
printf("Stack is empty\n");
return '\0';
}
return stack->data[stack->top--];
}
int isEmpty(Stack *stack) {
return stack->top == -1;
}
int isMatchingPair(char opening, char closing) {
if (opening == '(' && closing == ')') return 1;
if (opening == '{' && closing == '}') return 1;
if (opening == '[' && closing == ']') return 1;
return 0;
}
int areBracketsBalanced(char *expression) {
int length = strlen(expression);
Stack *stack = createStack(length);
for (int i = 0; i< length; i++) {
if (expression[i] == '(' || expression[i] == '{' || expression[i] == '[') {
push(stack, expression[i]);
} else if (expression[i] == ')' || expression[i] == '}' || expression[i] == ']') {
if (isEmpty(stack)) {
return 0;
} else {
char openingBracket = pop(stack);
if (!isMatchingPair(openingBracket, expression[i])) {
return 0;
}
}
}
}
return isEmpty(stack);
}
int main() {
char expression[] = "({[]})";
if (areBracketsBalanced(expression)) {
printf("The brackets are balanced\n");
} else {
printf("The brackets are not balanced\n");
}
return 0;
}
這個程序首先定義了一個棧結構,然后實現了創建棧、入棧、出棧等基本操作。接下來,我們定義了一個isMatchingPair
函數,用于判斷兩個括號是否匹配。areBracketsBalanced
函數遍歷輸入的字符串,遇到開括號就入棧,遇到閉括號就出棧并檢查是否匹配。最后,如果棧為空,說明括號匹配成功,否則失敗。
在main
函數中,我們測試了一個包含圓括號、花括號和方括號的字符串,如果括號匹配,輸出"The brackets are balanced",否則輸出"The brackets are not balanced"。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。