2016-09-23 4 views
-1

空の単一リンクリストがない場合、関数はパラメータリストのすべての要素を呼び出しオブジェクトにコピーします。パラメータリストから呼び出し元オブジェクトに要素をコピーしていますか?

void AnyList::preFour(const AnyList& otherList) { 

    bool found = false; 

    Node* checkPtr = otherList.ptrToFirst; 

    //find first 4 
    while (checkPtr != nullptr && !found) { 

     if (checkPtr->getData() == 4) { 
      found = true; 
     } 
     else 
      checkPtr = checkPtr->getPtrToNext(); 
    } 


    Node* current = ptrToFirst; 
    Node* copy = otherList.ptrToFirst; 

    while (current != checkPtr) { 


     current = current->getPtrToNext(); 
     copy = copy->getPtrToNext(); 
    } 
} 

これは私がこれまでのところ、私は、呼び出し元のオブジェクト(空のリスト)に、それらの要素をコピーしている間にある程度のパラメータリストをコピーする方法についていくつかのポインタを必要としているコードです。新しいノードを作成する必要はありますか?

+0

パラメータオブジェクトは次のようになります:1,2,3,4 =>呼び出し元のオブジェクトは1,2,3 – elequang

+1

です。フォーカスを 'STL containers'に移すことをお勧めします。そこにはたくさんのおいしさがあります。 –

答えて

0

この操作を行います。呼び出し元のオブジェクトのリストが空であるので

void AnyList::preFour(const AnyList& otherList) { 

    bool found = false; 

    Node* checkPtr = otherList.ptrToFirst; 

    //find first 4 
    while (checkPtr != nullptr && !found) { 

     if (checkPtr->getData() == 4) { 
      found = true; 
     } 
     else 
      checkPtr = checkPtr->getPtrToNext(); 
    } 

    Node* current; 
    Node* copy = otherList.ptrToFirst; 


    /* This node is just to facilitate in copying. 
     It actually stores no relevant data. 
     It will be deleted after we are done with copying.*/ 
    Node* dummy = new Node(); 
    current = dummy; 

    while (copy != checkPtr) { 

     Node* temp = new Node(); 
     current->next = temp; // Use appropriate method to set nextptr 
     current = current->getPtrToNext(); 

     *current = *copy; // Use appropriate copy constructor or other method 
     copy = copy->getPtrToNext(); 
    } 
    /* This method should return NULL if next pointer is not available. 
     If that is not so, just add a check here. 
    */ 
    ptrToFirst = dummy->getPtrToNext(); 
    delete dummy; 
} 

を、我々は最初の最初のノードのためのスペースを割り当てる必要があります。

Node* dummy = new Node(); 
    current = dummy; 

を我々は停止状態に達していない一方で、我々は、このループを使用して、オブジェクトのリストを呼び出すにパラメータリストから内容をコピーしておく:だから私は、最初のdummyノードを作成します。条件が成功するたびに新しいノードを作成する必要があります。私たちは、新しい要素をコピーするためのスペースを割り当てる必要があるためです。:コピーした後、私はdummy->getPtrToNext()、その後deletedummyノードであることをptrToFirstを割り当てることを

while (copy != checkPtr) { 

     Node* temp = new Node(); 
     current->next = temp; // Use appropriate method to set nextptr 
     current = current->getPtrToNext(); 

     *current = *copy; // Use appropriate copy constructor or other method 
     copy = copy->getPtrToNext(); 
    } 

注意。

+0

Node * currentの後にすべてを説明できますか? – elequang

関連する問題