【问题标题】:Having trouble printing a singly linked list stack recursively递归打印单链表堆栈时遇到问题
【发布时间】:2020-09-02 06:44:54
【问题描述】:

我目前无法弄清楚如何执行此操作。我现在的想法是让堆栈pop()this 每次在其内部递归调用print,但这对我不起作用。

template <class T>
void Stack<T>::print() const {  
    if (top->next == nullptr) {
        cout << "End of list" << endl;
    }
    else {
        cout << top->data;
        this->pop();
        print();
    }
}

当我通过 Stack&lt;int&gt; test 在我的 main 中声明一个 int 类型的 Stack 时,我收到错误 "passing const Stack&lt;int&gt; as 'this' argument discards qualifiers

【问题讨论】:

  • 你不能顺序输出包含 N 个元素且复杂度为 O(1) 的东西。:)
  • 您的问题是关于如何以 O(1) 时间复杂度打印链表,还是关于构建错误?请确保问题的标题是您所问问题的简短摘要。你实际上是在问一个问题。请花点时间刷新How to Askthis question checklist
  • @VladfromMoscow 哎呀,我看错了作业;我们实际上应该只是递归地打印它,它实际上并没有提及时间复杂度。
  • @Logan87654321 错误信息的意思是一些使用的函数top或pop不是常量函数。
  • 为了递归,函数应该在某个时候调用自己。你的函数在哪里调用自己?

标签: c++ recursion linked-list stack function-definition


【解决方案1】:

passing const Stack&lt;int&gt; as 'this' argument discards qualifiers

这是你的问题。你用const 限定了你的print 函数。这是一个承诺,您在打印时不会更改堆栈(这是一个合理的期望)。调用 pop 会改变堆栈,破坏承诺。

编译器报错信息中的“限定符”是const,所以“discards qualifiers”的基本意思是“放弃你不改变*this的承诺”。

【讨论】:

    【解决方案2】:

    对于初学者来说,该函数不是递归函数(正如您在更新问题之前展示的那样)。

    此外,当为空堆栈调用时(即指针 top 等于 nullptr 时),它具有未定义的行为。

    至于错误消息,函数pop 在从常量函数print 调用时更改了堆栈(它是一个非常量成员函数)。所以编译器会报错。

    因此假设函数print在输出它的值时会改变堆栈,那么它应该被声明为一个非常量函数。

    该函数可能如下所示。我假设函数push 或其类似物被声明为类似

    void push( const T & );
    

    你来了。

    template <class T>
    std::ostream & Stack<T>::print( std::ostream &os = std::cout ) 
    {
        if ( this->top )
        {
            os << top->data << ' ';
    
            auto value = top->data;
    
            this->pop();
    
            this->print( os );
    
            this->push( value );      
        }
    
        return os;
    }
    

    并且函数可以像这样调用

    Stack<int> test;
    
    //...
    
    test.print() << '\n';
    

    这是一个演示程序,显示了上面的函数,对标准类模板 std::stack 进行了微小的更改(因为您没有显示堆栈定义)。

    #include <iostream>
    #include <stack>
    
    template <class T>
    std::ostream & print( std::stack<T> &st, std::ostream &os = std::cout ) 
    {
        if ( not st.empty() )
        {
            os << st.top() << ' ';
    
            auto value = st.top();
    
            st.pop();
    
            print( st, os );
    
            st.push( value );      
        }
    
        return os;
    }
    
    int main() 
    {
        std::stack<int> st( std::stack<int>::container_type { 5, 4, 3, 2, 1 } );
    
        print( st ) << '\n';
    
        return 0;
    }
    

    程序输出是

    1 2 3 4 5 
    

    【讨论】:

      猜你喜欢
      • 2023-03-15
      • 1970-01-01
      • 2012-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-22
      • 2018-01-05
      • 1970-01-01
      相关资源
      最近更新 更多