Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

c++ - Linked List pushback member function implementation

I am a novice programmer and this is my second question on Stack Overflow.

I am trying to implement a pushback function for my Linked List by using a tail pointer. It seems straightforward enough, but I have a nagging feeling that I am forgetting something or that my logic is screwy. Linked Lists are hard!

Here is my code:

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;
}

Thank you for taking the time to read this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your pointing the wrong mPrev to the wrong node. And you never set mNext of the prior tail node if it was non-null to continue the forward chain of your list.

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...