2016-09-21 5 views
-1

私は初心者のプログラマです。これはStack Overflowに関する2番目の質問です。リンクリストのプッシュバックメンバ関数の実装

テールポインタを使用してリンクリストのプッシュバック機能を実装しようとしています。それは十分に簡単だと思われますが、私は何かを忘れている、または私の論理がうんざりしているという気分があります。リンクされたリストは難しいです!

template <typename T> 
void LinkedList<T>::push_back(const T n) 
{ 
Node *newNode; // Points to a newly allocated node 

// A new node is created and the value that was passed to the function is stored within. 
newNode = new Node; 
newNode->mData = n; 
newNode->mNext = nullptr; 
newNode->mPrev = nullptr; 

//If the list is empty, set head to point to the new node. 
if (head == nullptr) 
{ 
    head = newNode; 
    if (tail == nullptr) 
    { 
     tail = head; 
    } 
} 
else // Else set tail to point to the new node. 
    tail->mPrev = newNode; 
} 

がこれを読むために時間を割いていただき、ありがとうございます:

は、ここに私のコードです。

+1

まず、 'head'がnullの場合、' tail'もすでにnullになっているか、何かがひどく間違っているはずです。第2に、 'tail'がリストの最後のノードを指している場合、あなたの' newNode-> mPrev'が* that *( 'tail')を指すべきではないでしょうか?' tail = newNode; '? – WhozCraig

+1

コードを書く前に、データとしてボックスを、ボックス間をリンクとして使用して、リンクされたリストを紙に描画しておく必要があります。あなたが紙に書いていることをコードに翻訳してください。もしあなたがそうしたら、WhozCraigが指摘したように、あなたがやっていることが間違っているように思われます。 – PaulMcKenzie

+0

WhozCraig、あなたは絶対に正しいです。私のelseステートメントはnewNode-mPrev = tailだったはずです。私は愚かなエラーを起こしていることを知っていた!ポール、私はそれを紙の上に書きました。私はすべてそれを書いておくべきだった!アドバイスありがとう。 –

答えて

2

間違ったノードに間違ったmPrevを指しています。前のtailノードのmNextを決して設定していない場合は、リストのフォワードチェーンを続けるためにnullでない場合はありません。

template <typename T> 
void LinkedList<T>::push_back(const T n) 
{ 
    Node *newNode; // Points to a newly allocated node 

    // A new node is created and the value that was passed to the function is stored within. 
    newNode = new Node; 
    newNode->mData = n; 
    newNode->mNext = nullptr; 
    newNode->mPrev = tail; // may be null, but that's ok. 

    //If the list is empty, set head to point to the new node. 
    if (head == nullptr) 
     head = newNode; 
    else 
     tail->mNext = newNode; // if head is non-null, tail should be too 
    tail = newNode; 
} 
+0

おかげで、WhozCraig。本当に私がこのプロセスを理解するのを助けました。 –