我是一名新手程序员,这是我在Stack Overflow上的第二个问题。
我正在尝试使用尾指针为我的链表实现回送功能。这似乎很简单,但我有一种唠叨的感觉,我忘记了某些东西,或者说我的逻辑很棘手。链接列表很难!
这是我的代码:
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;
}
感谢您抽出宝贵时间阅读本文。
答案 0 :(得分:3)
您将错误的mPrev
指向错误的节点。并且如果先前的mNext
节点为非空,则永远不会设置tail
以继续列表的前向链。
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;
}