我正在尝试为模板化的双链表编写复制构造函数... 这是我到目前为止所做的:
// Copy Constructor
template <typename Item>
LinkedList<Item>::LinkedList(const LinkedList<Item> &s){
// Create an iterator for the other list
ListNode<Item> *node = s.head;
// Create a reference to use as an iterator for the new list
// Set it to the address of head of the new list
ListNode<Item> **curr_node = &head;
// Create a placeholder for the address of the previous node
ListNode<Item> *prev_node = NULL;
while(node != NULL){
*curr_node = new ListNode<Item>;
// If a prev_node address has been saved, initialize the new node's prev value
// If a prev_node hasn't been saved yet, this means it is the head and prev should
// be initialized to NULL
(*curr_node)->prev = prev_node;
// Set the new node data fields to that of the node in the other list
(*curr_node)->data = node->data;
// -------- Set up for next iteration -------
// Save the address of the current node to be used in the next node's prev_node
prev_node = *curr_node;
// Set the curr_node pointer to the address of the next node in the new list
curr_node = &((*curr_node)->next);
// Set the node pointer to the next node in other list
node = node->next;
}
// Set the tail after all the nodes have been copied
tail = prev_node;
}
当我在我的测试人员中调用此代码时:
LinkedList<int> ll;
ll.insert_back(5);
ll.insert_back(10);
ll.insert_back(15);
LinkedList<int> ll1 = ll;
cout << "Printing contents of copied list: "; ll1.print();
我在valgrind中遇到此错误:
Contents of list to be copied: [5] -> [10] -> [15]
==4624== Conditional jump or move depends on uninitialised value(s)
==4624== at 0x401077: LinkedList<int>::print() (LinkedList.cc:159)
==4624== by 0x400D7B: main (tester.cpp:54)
==4624==
==4624== Conditional jump or move depends on uninitialised value(s)
==4624== at 0x40109E: LinkedList<int>::print() (LinkedList.cc:155)
==4624== by 0x400D7B: main (tester.cpp:54)
我的print()函数的第153,155,159行:
153: ListNode<Item> *end = head;
155: while(end != NULL){
159: if(end->next != NULL)
所以我得出的结论是,end永远不会被初始化,这意味着head是NULL或设置为某个垃圾值......任何人对此有什么想法?我哪里错了?
答案 0 :(得分:0)
您似乎想要替换
行curr_node = &((*curr_node)->next);
与
*curr_node = &(node->next);
因为curr_node
之前在while循环中设置为new ListNode<Item>
。
好奇,为什么curr_node是一个指向节点指针的指针?