任何人都可以帮助我使这段代码工作 [英] Can anyone help me to make this code to work
本文介绍了任何人都可以帮助我使这段代码工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试平衡这些字符,我收到一些错误,任何人都可以尝试查看我需要更改的代码
错误是分段错误: 11
我尝试过:
i am trying to balance these characters , i receiving some errors , can anyone try to see my code where i need the changes
Error is "Segmentation fault: 11"
What I have tried:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char T;
#include "stack.h"
int isBalanced(char s[100])
{
Stack *stack;
int n=strlen(s);
int i;
for(i=0;i<n;i++)
{
if(s[i]=='(' || s[i]=='[' || s[i]=='{')
{
Push(&stack,s[i]);
}
else if(s[i]==')' || s[i]==']' || s[i]=='}')
{
if(IsEmptyStack(stack))
{
return 0;
}
else if(Top(stack)!=s[i])
Pop(stack);
}
}
if(IsEmptyStack(stack))
return 1;
else
return 0;
}
int main()
{
char s1[100]="((()))", s2[100]="((())(";
if(isBalanced(s1))
printf("Balanced | \n");
else
printf("Not balanced | \n");
if(isBalanced(s2))
printf("Balanced | \n");
else
printf("Not balanced | \n");
return 0;
}
推荐答案
你的意思是
Do you mean
#include <iostream>
#include <cstring>
#include <stack>
using namespace std;
int isBalanced(char s[100])
{
stack<char> stk;
int n=strlen(s);
int i;
for(i=0;i<n;i++)
{
if(s[i]=='(' || s[i]=='[' || s[i]=='{')
{
stk.push(s[i]);
}
else if(s[i]==')' || s[i]==']' || s[i]=='}')
{
if(stk.empty())
{
return 0;
}
else if(stk.top() != s[i])//<--- What's the purpose of this line?
stk.pop();
}
}
if(stk.empty())
return 1;
else
return 0;
}
然而我无法猜出标记线的用途
However I can't guess the purpose of the marked line
你的算法错了。
当你遇到一个开头([{
,你把它推到堆栈上,到目前为止,那么好。
当你遇到收盘)]}
时,你检查堆栈是否为空,好吧。
然后你应该检查一下右括号与堆栈上的开头匹配,否则失败。
如果(
位于堆栈顶部,)
是唯一允许的。
您必须重新考虑您的算法。
遇到时a,打开括号,我会在堆栈上推送结束副本,它会简化以后的检查。
Your algorithm is wrong.
When you encounter an opening([{
, you push it on stack, so far, so good.
When you encounter a closing)]}
, you check if stack is empty, ok.
then you should check if the closing parenthesis is matching the opening one on stack, otherwise, it is a fail.
if(
is on top of stack,)
is the only one allowed.
You have to rethink your algorithm.
When encountering a, opening parenthesis, I would push the closing counterpart on stack, it simplify later checking.
这篇关于任何人都可以帮助我使这段代码工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文