【问题标题】:C++ understanding issue- linked lists and stackC++ 理解问题链表和堆栈
【发布时间】:2014-08-06 00:21:41
【问题描述】:

我必须编写一个代码,使用 stacklinked 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


【解决方案1】:

我会推荐以下方法:

  • 考虑你的算法忽略语言细节。堆栈是正确的方法,但您无需考虑如何实现堆栈,除非您考虑了算法。

  • 决定您需要一个给定的数据结构后,在发明您自己的数据结构之前问问自己它是否已经存在于 C++ (std::stack) 中。

  • 使用 C++ 习惯用法而不是 C 习惯用法(即使用迭代器 begin() 和 end() 不索引)除此之外,这将防止您的 exp[i] 错误。

  • 不要让一个班级做不止一件事。如果您需要一个堆栈,则创建一个堆栈类,而不是让您的解析类参与堆栈实现。首先它更容易考虑检查算法,其次堆栈类可以在其他地方重用。

在大纲中,您的解决方案将使用迭代器来检查字符串的字符,并使用 std::stack。任何地方都不需要 new 或指针。

【讨论】:

  • 我在谷歌上搜索了更多内容并找到了一些解释,我知道如何仅使用 bool Pairs 和 bool CheckIfBalanced 来解决此任务,但我仍然不清楚:S 是否可以解决它还有其他方法吗?正如我所说,我们必须使用节点、链表和堆栈:S
  • 我不明白你的评论:“我们必须使用节点、链表和堆栈......”。您的任务是检查平衡括号还是使用各种不必要的数据结构?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-31
  • 2014-11-12
  • 1970-01-01
  • 2015-12-18
  • 2011-09-16
相关资源
最近更新 更多