【问题标题】:Linked List pushback member function implementation链表回推成员函数实现
【发布时间】:2017-01-29 03:19:51
【问题描述】:

我是一名新手程序员,这是我关于 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;
}

感谢您抽出宝贵时间阅读本文。

【问题讨论】:

  • 首先,如果head 为空,tail 也应该已经为空,或者出现了可怕的错误。其次,如果tail指向列表中的最后一个节点,你的newNode-&gt;mPrev不应该指向那个tail),然后设置tail = newNode;
  • 在编写任何代码之前,您应该在纸上绘制链表,使用框作为数据,框之间的线作为链接。然后将你在纸上看到的内容转化为代码——如果你这样做了,显然你所做的似乎是错误的,正如 WhozCraig 指出的那样。
  • WhozCraig,你说得对。我的 else 语句应该是 newNode-mPrev = tail。我知道我犯了一个愚蠢的错误!保罗,我确实在纸上写了一些。我应该都写出来的!谢谢你的建议。
  • @RyanSwanson 是的,但你永远不会在非空 tail 的情况下设置 tail-&gt;mNext = newNode(你可以从非空 head 推断),这对此至关重要去工作。请参阅下面的答案。

标签: c++ linked-list push-back


【解决方案1】:

您将错误的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;
}

【讨论】:

  • 非常感谢,WhozCraig。真的帮助我掌握了这个过程。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多