括號的匹配,順序棧方法
阿新 • • 發佈:2019-02-05
<img src="https://img-blog.csdn.net/20160929104232493?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" /><img src="https://img-blog.csdn.net/20160929104239274?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" /><img src="https://img-blog.csdn.net/20160929104232493?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />1.標頭檔案:sqstack.h,包含定義順序棧資料結構的程式碼、巨集定義、要實現演算法的函式的宣告; #ifndef SQSTACK_H_INCLUDED #define SQSTACK_H_INCLUDED #define MaxSize 100 typedef char ElemType; typedef struct { ElemType data[MaxSize]; int top; //棧指標 } SqStack; //順序棧型別定義 void InitStack(SqStack *&s); //初始化棧 void DestroyStack(SqStack *&s); //銷燬棧 bool StackEmpty(SqStack *s); //棧是否為空 int StackLength(SqStack *s); //返回棧中元素個數——棧長度 bool Push(SqStack *&s,ElemType e); //入棧 bool Pop(SqStack *&s,ElemType &e); //出棧 bool GetTop(SqStack *s,ElemType &e); //取棧頂資料元素 void DispStack(SqStack *s); //輸出棧 #endif // SQSTACK_H_INCLUDED 2.原始檔:sqstack.cpp,包含實現各種演算法的函式的定義 #include <stdio.h> #include <malloc.h> #include "sqstack.h" void InitStack(SqStack *&s) { s=(SqStack *)malloc(sizeof(SqStack)); s->top=-1; } void DestroyStack(SqStack *&s) { free(s); } int StackLength(SqStack *s) //返回棧中元素個數——棧長度 { return(s->top+1); } bool StackEmpty(SqStack *s) { return(s->top==-1); } bool Push(SqStack *&s,ElemType e) { if (s->top==MaxSize-1) //棧滿的情況,即棧上溢位 return false; s->top++; s->data[s->top]=e; return true; } bool Pop(SqStack *&s,ElemType &e) { if (s->top==-1) //棧為空的情況,即棧下溢位 return false; e=s->data[s->top]; s->top--; return true; } bool GetTop(SqStack *s,ElemType &e) { if (s->top==-1) //棧為空的情況,即棧下溢位 return false; e=s->data[s->top]; return true; } void DispStack(SqStack *s) //輸出棧 { int i; for (i=s->top;i>=0;i--) printf("%c ",s->data[i]); printf("\n"); } 3.main.cpp完成測試 #include <stdio.h> #include "sqstack.h" int main() { char c; char st[50]; int d=1, i; SqStack *s; InitStack(s); printf("請輸入表示式:"); scanf("%s", st); for(i=0; st[i]!='\0'&&d; i++) { switch(st[i]) { case'(': case'[': case'{': Push(s, st[i]); break; case')': Pop(s, c); if(c!='(') d=0; break; case']': Pop(s, c); if(c!='[') d=0; break; case'}': Pop(s,c); if(c!='{') d=0; break; } } if(StackEmpty(s)&&d==1) printf("配對正確!!\n"); else printf("配對錯誤!!\n"); return 0; }