链接堆栈复制构造函数

时间:2016-10-08 17:24:40

标签: c++

template<typename T>
LinkedStack<T>::LinkedStack(const LinkedStack<T> &other) {
Node<T> *temp = other.stktop;
if (other.stktop != nullptr) {

    Node<T> *newnode = new Node<T>;
    newnode = temp;

    while (temp->next != nullptr) {
        temp = temp->next;
        newnode->next = temp;
    }
}
}

这是我的复制构造函数。

template <typename U>
struct Node {
    U data;
    Node<U> *next;
};

Node<T> *stktop;

这是我的struct节点,位于我的LinkedStack类的私有部分。 我尝试遵循编写复制构造函数的逻辑,然后我想出了这个代码。但是它不起作用。任何想法有什么问题?

1 个答案:

答案 0 :(得分:0)

类似的东西:

template<typename T>
LinkedStack<T>::LinkedStack(const LinkedStack<T> &other)
{
    // Create first node
    if (!other.stktop) // Use pointer to bool cast
    {
        stktop = new Node<T>;
        // Copy data. This is the simplest copy if U support it.
        stktop->data = other.stktop->data;
    }
    else
    {
        stktop = nullptr; // Very important otherwise its value is undefined
        return;
    }

    auto pothernode = other.stktop;
    auto pthisnode = stktop;

    // Iterate overall the elements
    while (pothernode->next)
    {
        pthisnode->next = new Node<T>;
        pthisnode->next->data = pothernode->next->data;

        pothernode = pothernode->next;
        pthisnode = pthisnode->next;
    }
}

请注意,所有节点都在堆上分配,因此不要忘记删除它们。我建议使用std::unique_ptrstd::shared_ptr代替纯指针。

一些可能的优化:

template<typename T>
LinkedStack<T>::LinkedStack(const LinkedStack<T> &other)
{
    const auto& pothernode = other.stktop;
    auto& pthisnode = stktop;
    pthisnode = nullptr;

    // Iterate overall the elements
    while (pothernode)
    {
        pthisnode = new Node<T>;
        pthisnode->data = pothernode->data;

        pothernode = pothernode->next;
        pthisnode = pthisnode->next;
    }
}