【问题标题】:Printing a double linked list with const pointer [closed]使用 const 指针打印双链表 [关闭]
【发布时间】:2014-07-08 19:41:35
【问题描述】:

我不明白为什么一个功能不起作用。它与 const 指针有关。

//prints the contents of the list interval [begin,end)
//to the output stream os; values should be separated by spaces
void print(const Node* begin, const Node* end, ostream& os)
{
    Node* current_node = begin;
    do
    {
        os << current_node->value << " ";
        current_node = current_node->next;
    }
    while(current_node != end);
    os << endl;
}

我不能改变这个函数的头部。

这个功能会起作用吗?

//erases the list interval [begin,end)
//attention: this should not erase 'end', see remarks above
void erase(Node* begin, Node* end){
    Node* current_node = begin;
    Node* next_node = begin->next;
    Node* begin_node = begin->prev;
    while(current_node != end){
        next_node->prev = current_node->prev;
        begin_node->next = next_node;
        delete current_node;
        current_node = next_node;
        next_node = current_node->next;
    }
}

这是节点的结构

struct Node
{
    int value;
    struct Node* next;
    struct Node* prev;
};

【问题讨论】:

  • 实际上有什么问题?编译器错误、运行时崩溃、意外结果?您的问题不清楚。

标签: c++ c printing delete-operator doubly-linked-list


【解决方案1】:

这行不对:

Node* current_node = begin;

由于begin 的类型是const Node*,您需要将current_node 的类型更改为const Node* 才能使该行工作:

const Node* current_node = begin;

关于你的函数erase,我看到了一些问题:

  1. 如果begin-&gt;prev 为NULL,你会在该行遇到问题:

    begin_node->next = next_node;
    
  2. end 是否应该为 NULL?如果没有,我在任何地方都看不到 end-&gt;prev 设置为 begin_node。没有它,双向链表就会被破坏。

【讨论】:

  • 那么有可能做到这一点吗? current_node = current_node->下一个;那为什么这可能呢?
  • @SvenBamberger,是的,你可以使用current_node = current_node-&gt;next;
  • @R Sahu 好的,但是为什么呢?不也是一个常量吗?
  • @SvenBamberger,const Node* 类型的变量的值可以通过赋值来改变,只要 RHS 上的表达式类型可以转换为const Node*。也许您正在考虑声明为 const 的变量,例如 const i = 10;,其值以后无法更改。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多