stack解决括号问题

问题描述:

Write a program to implement “Parse Parentheses” (Algorithm 3-9, discussed in the class),

matching braces rather than parentheses. In your implementation, push the line number

into the stack rather than the opening brace. When an error occurs, print the line number

for the unmatched opening brace or unmatched closing brace.

代码:

#include<stdio.h>

#include<assert.h>

#include<string.h>

 

#define MaxSize 100

 

typedef char SDataType;

typedef struct Stack

{

int top;

SDataType _arry[MaxSize];

}Stack;

 

int IsBrackets(char arry[], int i)

{

if (('(' == arry[i]) || (')' == arry[i]) || ('[' == arry[i]) || (']' == arry[i]) || ('{' == arry[i]) || ('}' == arry[i]))

return 1;//是括号

else

return 0;

}

 

int StackSize(Stack* ps)

{

assert(ps != NULL);

return ps->top;

}

 

void StackPush(Stack* ps, SDataType data)

{

assert(ps != NULL);

if (ps->top == MaxSize)

return;

else

{

ps->_arry[ps->top] = data;

ps->top++;

}

}

 

void StackPop(Stack* ps)

{

assert(ps != NULL);

if (ps->top)

ps->top--;

 

}

 

int StackEmpty(Stack* ps)

{

assert(ps != NULL);

if (0 == ps->top)

return 1;

else

return 0;

}

 

void StackInit(Stack* ps)

{

assert(ps != NULL);

ps->top = 0;

}

 

void MatchBrackets(Stack* ps, int sz, char arry[])

{

int i = 0;

int k = 0;//因为传的是指针,所以要定义一个形参

assert(ps != NULL);

//char ch = 0;

while (i < sz)

{

printf("arry[i]: %c", arry[i]);

if (IsBrackets(arry, i))//是括号

{

//如果是左括号,入栈

if (('(' == arry[i]) || ('[' == arry[i]) || ('{' == arry[i]))

{

StackPush(ps, arry[i]);

i++;

continue;

}

else if ((')' == arry[i]) || (']' == arry[i]) || ('}' == arry[i]))

{

if (0 == ps->top) //判断栈是否为空,若为空,则右括号比左括号多

{

printf("右括号比左括号多!\n");

return;

}

else

{

k = ps->top;

char ch = ps->_arry[--k];

if (((')' == arry[i]) && ('(' == ch)) ||

((']' == arry[i]) && ('[' == ch)) ||

(('}' == arry[i]) && ('{' == ch)))

{

 

StackPop(ps);

i++;

continue;

}

else

{

printf("括号匹配出错!\n");

return;

}

}

}

}

else //不是括号,不用操作,直接向后走

{

i++;

}

}

if (!StackEmpty(ps))

{

printf("左括号比右括号多!\n");

}

else

{

printf("匹配正确!\n");

}

 

}

 

void main()

{

char arry[] = "avclsd[]lsi(l)()}";

int sz = 100, len;

Stack ps;

StackInit(&ps);

len = StackSize(&ps);

printf("len: %d\n", len);

char data = 'a';

//StackPush(&ps, data);

MatchBrackets(&ps, sz, arry);

len = StackSize(&ps);

printf("len: %d\n", len);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值