我必須做一個代碼,檢查括號是否平衡使用堆棧和鏈表。 這裏是我的代碼,我使用了很多來自課堂的教程和功能點演示文稿,還有我的朋友的一點點幫助。 但是,任何人都可以解釋'詮釋流行'和'檢查'部分,一行一行地發生了什麼(作爲評論部分,我不明白)?我在理解這部分C++(實現的stacks和l.lists)時遇到了問題,而且我沒有任何人可以解釋它以及誰有時間。我嘗試了很多東西,但我真的不明白。 P.S.代碼的工作原理,因爲它應該 謝謝你們!C++瞭解問題鏈接列表和堆棧
#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;
}
使用調試器,並執行它一步一步... – jsantander
我建議你閱讀了關於指針和結構/類,那麼你就會明白了很多這是怎麼回事。不要以爲你從別的地方得到代碼,這是正確的。你對這段代碼持懷疑態度。 – Simon