0

テンプレート化された二重リンクリストのコピーコンストラクターを作成しようとしています...これまでのところ、次のとおりです。

// 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 であるか、何らかのジャンク値に設定されています...これについて考えている人はいますか? どこが間違っているのですか?

4

1 に答える 1

0

ラインを交換したいようです

curr_node = &((*curr_node)->next);

*curr_node = &(node->next);

while ループ内で以前curr_nodeに設定されたので。new ListNode<Item>

ちょっと興味がありますが、なぜ curr_node がノードへのポインターへのポインターなのですか?

于 2013-10-22T00:15:32.293 に答える