#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
const int STACK_INIT_SIZE=100;
const int STACKINCREMENT=10;
typedef char SElemType;
typedef struct
{
SElemType *elem;
int top;
int stacksize;
int increment;
}SqStack;
// 初始化堆疊
void InitStack(SqStack&S,int maxsize=STACK_INIT_SIZE,int incresize=STACKINCREMENT)
{
S.elem=new SElemType[STACK_INIT_SIZE];
S.top=-1;
S.stacksize=maxsize;
S.increment=incresize;
}
//入堆疊
void Push(SqStack&S,SElemType e)
{
if(S.top==S.stacksize)
{
S.stacksize=S.stacksize+STACKINCREMENT;
SElemType *elem=new SElemType[S.stacksize];
for(int i=0;i<=S.top;i++)
elem[i]=S.elem[i];
delete []S.elem;
S.elem=elem;
}
S.elem[++S.top]=e;
}
//檢查空堆疊
bool StackEmpty(SqStack S)
{
if(S.top==-1)
return true;
else return false;
}
//取堆疊頂元素
bool GetTop(SqStack S,SElemType &e)
{
if(S.top==-1) return false;
e=S.elem[S.top];
return true;
}
//讓堆疊頂元素出堆疊
bool Pop(SqStack &S,SElemType&e)
{
if(S.top==-1) return false;
e=S.elem[S.top];
S.top--;
return true;
}
//括號匹配
bool matching(char exp[])
{
SqStack S;
InitStack(S);
int state=1;
char e;
char ch=*exp++;
while(ch != '#' &&state)
{switch(ch)
{
switch (ch) {
case'(':
{
Push(S, ch);
break;
}
case'[':
{
Push(S, ch);
break;
}
case'{':
{
Push(S, ch);
break;
}
case')':
{
if (!StackEmpty(S) && GetTop(S,e)== '(')
Pop(S, e);
else state = 0;
break;}
case']':
{
if (!StackEmpty(S) && GetTop(S,e) == '[')
Pop(S, e);
else state = 0;
break;}
case'}':
{
if (!StackEmpty(S) && GetTop(S,e) == '{')
Pop(S, e);
else state = 0;
break;}
}
default:break;
}
ch=*exp++;
}
if(state&&StackEmpty(S))
return true;
else return false;
}
//主函式
int main ()
{
int max=50;//陣列容量
char a[max];
cout<<"輸入括號運算式(以“#”結尾)"<<endl;
cin>>a;
if(matching(a))
{
cout<<"括號匹配"<<endl;
cout<<"\n";
}
else cout<<"括號不匹配"<<endl;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/72864.html
標籤:C語言
上一篇:一個關于LeapMotion指骨方向資料使用的小問題
下一篇:C語言題目求助!
