您的位置:首页 > 理论基础 > 数据结构算法

【数据结构】用栈实现括号匹配的检验

2015-11-10 14:53 405 查看


用栈实现括号匹配的检验.cpp

#include<iostream>

#include<string>

using namespace std;

typedef char SElemType;

typedef struct

{

SElemType *base;

SElemType *top;

int stacksize;

}SqStack;

void InitStack(SqStack &S)//构造一个空栈

{

S.base = (SElemType *)malloc(20 * sizeof(SElemType));

if (!S.base)

{

cout << "存储分配失败!" << endl;

exit(0);

}

S.top = S.base;

S.stacksize = 20;

}

void Push(SqStack &S, SElemType e)//进栈

{

if ((S.top - S.base) >= S.stacksize)

{

S.base = (SElemType *)malloc((S.stacksize + 10)* sizeof(SElemType));//如果栈满,申请新空间

if (!S.base)

{

cout << "存储分配失败!" << endl;

exit(0);

}

S.top = S.base + S.stacksize;

S.stacksize += 10;

}

*S.top++ = e;

}

int StackEmpty(SqStack S) { /*判断栈是否为空*/

if (S.top == S.base) return 1;

else return 0;

}

int Pop(SqStack &S, SElemType &e)//出栈

{

if (S.top == S.base)

return 0;

e = *--S.top;

return 0;

}

int Comp(SElemType a, SElemType b)

{

if ((a == '('&&b != ')')|| (a == '['&&b != ']')|| (a == '{'&&b != '}'))

return 0;

else return 1;

}

int Match()

{

SqStack S;

InitStack(S);

SElemType e[20], e1;

cout << "请输入一串括号:" << endl;

fgets(e, 20, stdin);

if ('\n' == e[strlen(e) - 1])

e[strlen(e) - 1] = 0;

cout << "您输入的字符串为:" << e << endl;;

for (int i = 0; e[i] != '\0'; i++)

{

switch (e[i])

{

case '(':

case '[':

case '{':

Push(S, e[i]);

break;

case ')':

case ']':

case '}':

if (StackEmpty(S))

{

printf("%*s右括号多余\n", e[i + 1], " ");

return 0;

}

else Pop(S, e1);

if (!Comp(e1, e[i]))

{

cout<<"左右匹配出错"<<e[i + 1]<<" ";

return 0;

}

}

if (!StackEmpty(S))

{

cout<<"左括号多余"<< e[i]<<" "<< endl;;

return 0;

}

else

{

cout << "匹配正确" << endl;;

return 1;

}

}

}

int main()

{

Match();

return 1;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: