c語言通過棧判斷括號匹配是否配對
更新時間:2023年09月22日 09:16:25 作者:gnip
前面實現(xiàn)了棧的基本數(shù)據(jù)結構,這里來做一個聯(lián)系,用棧來解決一道比較常見的算法題,就是括號配對是否滿足規(guī)則,文中有相關的代碼示例供大家參考,需要的朋友可以參考下
實現(xiàn)
描述
給定一組括號,判斷是否滿足配對。
代碼
#include<stdio.h> #include<assert.h> #include<stdlib.h> #define bool char #define true 1 #define MAX_LEN 10 #define false 0 typedef char ElementType; typedef struct Stack { int top; ElementType stackList[MAX_LEN]; } Stack; bool fn(char arr[], int len, Stack* S); bool push(Stack* S, ElementType data); bool pop(Stack* S, ElementType* x); bool intStack(Stack* S); int main() { Stack S; intStack(&S); char brackList[] = {'(', '{','(',')','}','{','}','}' }; printf("%d", fn(brackList, sizeof(brackList) / sizeof(brackList[0]), &S)); } bool fn(char arr[], int len, Stack* S) { for (int i = 0; i < len; i++) { if (arr[i] == '{' || arr[i] == '(') { push(S,arr[i]); printf("%c", arr[i]); } else { if (S->top == 0) { return false; } ElementType topData; pop(S, &topData); if (topData == '(' && arr[i] != ')') { return false; } else if (topData == '{' && arr[i] != '}') { return false; } } } if (S->top == 0) { return true; } return false; } //初始化 bool intStack(Stack* S) { for (int i = 0; i < MAX_LEN; i++) { S->stackList[i] = 0; } S->top = 0; return true; } //入棧 bool push(Stack* S,ElementType data) { S->top++; S->stackList[S->top] = data; return true; } //出棧 bool pop(Stack* S, ElementType *x) { *x = S->stackList[S->top]; S->stackList[S->top] = 0; S->top--; return true; }
到此這篇關于c語言通過棧判斷括號匹配是否配對的文章就介紹到這了,更多相關c語言判斷是否配對內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!