链表推回成员功能实现



我是一名新手程序员,这是我关于堆栈溢出的第二个问题。

我正试图通过使用尾部指针来实现链表的推回功能。这看起来很简单,但我有一种唠叨的感觉,我忘记了什么,或者我的逻辑很古怪。链表很难!

这是我的代码:

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

感谢您花时间阅读本文。

您将错误的mPrev指向错误的节点。并且,如果前一个tail节点的mNext为非空,则永远不会设置它来继续列表的前向链。

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

相关内容

  • 没有找到相关文章