我正在用 C++ 编写一个程序,它实现了一个双向链表,每个节点中都包含一个字符。我通过附加功能插入字符:
doubly_linked_list adam;
adam.append('a');
该功能实现如下:
//Append node
node* append(const item c){
//If the list is not empty...
if(length){
//maintain pointers to end nodes
node* old_last_node = last;
node* new_last_node = new node;
//re-assign the double link and exit link
old_last_node->next = new_last_node;
new_last_node->back = old_last_node;
new_last_node->next = NULL;
//re-assign the last pointer
last = new_last_node;
}
//If this is the first node
else{
//assign first and last to the new node
last = first = new node;
//assign nulls to the pointers on new node
first->next = first->back = NULL;
}
//increase length and exit
++length;
return last;
}
但是,我认为存在一个问题,可能与 C++ 处理字符的方式有关。当我去打印我的列表时,不知何故我从来没有得到我已经附加到我的列表中的要打印的字符。这是我用来打印的:
//Friendly output function
friend std::ostream& operator << (std::ostream& out_s, const doubly_linked_list& source_list){
//create iteration node pointer
node* traverse_position = source_list.first;
//iterate through, reading from start
for(int i = 1; i <= source_list.length; ++i){
//print the character
out_s << (traverse_position->data);
traverse_position = traverse_position->next;
}
//return the output stream
return out_s;
}
我只是在打印时得到废话。它打印出我从未添加到列表中的字符——你知道,只是来自内存中某处的字符。这可能是什么原因造成的?