我正在尝试为模板化的双链表编写一个复制构造函数......这是我到目前为止所拥有的:
// 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 或设置为一些垃圾值......有人对此有任何想法吗?我哪里错了?