C++ 使用常量指针打印双链接列表

C++ 使用常量指针打印双链接列表,c++,c,printing,delete-operator,doubly-linked-list,C++,C,Printing,Delete Operator,Doubly Linked List,我不明白为什么一个函数不起作用。它与常量指针有关 //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

我不明白为什么一个函数不起作用。它与常量指针有关

//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;
}
这是节点的结构

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

这一行不对:

Node* current_node = begin;
由于
begin
的类型是
const Node*
,因此需要将
当前节点的类型更改为
const Node*
,该行才能工作:

const Node* current_node = begin;
关于擦除功能,我发现了一些问题:

  • 如果
    begin->prev
    为空,您将在行中遇到问题:

    begin_node->next = next_node;
    
  • end
    是否应为空?如果没有,我看不到
    end->prev
    设置为
    begin\u节点的任何地方。否则,双链接列表将被破坏


  • 到底是什么问题?编译器错误、运行时崩溃、意外结果?你的问题不清楚。那么有可能做到这一点吗?当前节点=当前节点->下一步;那么什么时候才有可能呢?@SvenBamberger,是的,你可以使用
    current\u node=current\u node->next@R Sahu可以,但为什么?它不也是常量吗?@SvenBamberger,只要RHS上的表达式类型可以转换为
    const Node*
    ,类型为
    const Node*
    的变量的值就可以通过赋值进行更改。也许您正在考虑声明为常量的变量,比如
    consti=10,其值以后无法更改。
    
    begin_node->next = next_node;