c++;输出和输入单个字符 >我正在编写一个C++程序,它实现了一个双链表,它在每个节点中都有一个字符。我通过追加功能插入字符: doubly_linked_list adam; adam.append('a');
此功能的实现如下所示:c++;输出和输入单个字符 >我正在编写一个C++程序,它实现了一个双链表,它在每个节点中都有一个字符。我通过追加功能插入字符: doubly_linked_list adam; adam.append('a');,c++,list,linked-list,char,cout,C++,List,Linked List,Char,Cout,此功能的实现如下所示: //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;
//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;
}
//友好的输出函数
friend std::ostream&operator在append()
函数中,您在哪里分配值c
?我担心您可能过于关注双链接列表部分,而对存储数据部分关注不够。:) 在append方法中,没有实际将项目放入新节点的位置。当您转到打印时,它只打印内存位置中碰巧存在的任何值(一些随机值)。正如其他人已经提到的,您忘记存储假定要追加的字符。犯这样的错误是合理的。为了避免将来出现这种情况,您可以让编译器帮助您
大多数编译器都会对技术上还可以,但可能不是您真正想要做的事情提供警告。在本例中,您声明了参数c
,但从未使用过它。启用警告后,编译器可能会注意到这一点并告诉您没有使用它。这可能已经足够提醒您,您还没有完成编写该函数
GCC启用常见警告的选项是-Wall
。(这是“W”代表“警告”,加上“所有”;它与墙壁无关。但也不是所有的警告。)例如:
g++ -Wall list-program.cpp
g++-Wall list-program.cpp
其他编译器也有类似的选项。查看编译器文档以了解详细信息。这是家庭作业,是吗?因为,否则,每个节点包含一个字符的双链接列表在内存上是非常浪费的(除非这些列表不需要包含太多字符)。四字节指针大约有800%的开销。你确定要这样做吗?