頭檔案中
#include<stdio.h>#include<stdlib.h>typedef char Elem;typedef int status;#define MAXSIZE 100#define ERROR 0#define OK 1typedef struct{ Elem data[MAXSIZE]; int top;}SqStack;//初始化void Initstack(SqStack &S){ if(!S.data) exit(-1); S.top = 0;}//入堆疊status Push(SqStack &S,Elem e){ if(S.top==MAXSIZE) { printf("堆疊滿了\n"); return ERROR; } S.data[S.top++] = e; return OK;}//出堆疊status Pop(SqStack &S){ if(S.top==0) return ERROR; S.top--;}//獲得堆疊頂元素status getTop(SqStack S,Elem &e){ if(S.top==0) return ERROR; e = S.data[S.top-1]; return OK;}
//括號匹配status Match(SqStack &S){ printf("---------------輸入想要匹配的括號-----------------\n\n"); printf(" 括號范圍[]、{}、()\n"); char str[MAXSIZE]; gets(str); printf("\n"); Elem pre = '#';//假如第一個括號是右括號,則與其匹配,當然肯定匹配錯誤 int i=0; while(str[i]!='\0') { if(str[i]=='{'||str[i]=='['||str[i]=='(') { Push(S,str[i]); i++; continue; } if(getTop(S,pre)) { if((pre=='{'&&str[i]=='}')||(pre=='['&&str[i]==']')||(pre=='('&&str[i]==')')) { Pop(S); i++; }else{ printf("匹配錯誤\n"); printf("\n"); printf("----------------------end----------------------"); return ERROR; } }else{ printf("堆疊空了或輸入的第一個是左括號\n\n"); printf("----------------------end-------------------------"); return ERROR; } } if(S.top==0){ printf("匹配成功\n"); printf("\n"); printf("-----------------------end-------------------------"); }else{ printf("匹配錯誤\n"); printf("\n"); printf("------------------------end------------------------"); }}
主函式
#include"StringMatch.h"int main(){ SqStack S; Initstack(S); Match(S);}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/67352.html
標籤:C
上一篇:C語言輸入帶空格的字串
