【发布时间】:2014-08-06 00:21:41
【问题描述】:
我必须编写一个代码,使用 stack 和 linked list 检查括号是否平衡。 这是我的代码,我使用课堂上的许多教程和 power point 演示文稿以及我朋友的一点点帮助制作的。 但是,任何人都可以逐行解释“int pop”和“check”部分下发生的事情(我把它作为注释部分我不明白)?我在理解 c++ 的这一部分(已实现的堆栈和 l.lists)方面遇到问题,而且我没有任何人可以解释它并且有时间。我尝试了很多东西,但我真的不明白。 附:代码可以正常工作 谢谢各位!
#include<iostream>
#include <string>
using namespace std;
struct node
{
char data;
node *link;
};
int pop(node *&stack) //node that points to address of a stack?
{
char result;
node *top=new node; //how can i explain this?
top=stack; //why are we equalizing top with stack?
result=top->data;//i dont understand
stack=top->link;//dont understand
delete top;
return result;
}
bool Pairs(char openP,char closedP)
{
if(openP == '(' && closedP == ')') return true;
else if(openP == '{' && closedP == '}') return true;
else if(openP == '[' && closedP == ']') return true;
else return false;
}
bool Check(string exp)
{
int i=0;
node *stack=NULL;
while(exp[i])
{
if(exp[i]=='(' || exp[i]=='[')
{
node *neww=new stack;//dont understand
neww->data=exp[i];//dont understand
neww->link=stack; //-II-
stack=neww; //-II-
}
if(exp[i]==')' || exp[i]==']')
{
if(stack==NULL)
return 0;
else if (Pairs(pop(stack), exp[i])==0) //what does mean this part in parentheses?
return 0;
}
i++;
}
if(stack==NULL)
return 1;
else
return 0;
}
int main()
{
string exp;
cout<<"Enter parentheses:\n";
cin>>exp;
if(Check(exp)!=0)
cout<<"P. are balanced";
else
cout<<"P. are not balanced";
return 0;
}
【问题讨论】:
-
使用调试器,一步一步执行……
-
我建议您阅读有关指针和结构/类的内容,然后您将了解更多发生的事情。不要仅仅因为你从其他地方得到代码就认为它是正确的。您对此代码的怀疑是正确的。
标签: c++ linked-list stack parentheses