简体   繁体   English

深拷贝链表

[英]Deep copying linked list

I'm trying to implement a stack on the heap using a linked list.我正在尝试使用链表在堆上实现堆栈。 However, for using the 'list' function I need to create a deep copy of the linked list, which i'm not completely sure how it's done.但是,为了使用“列表”function,我需要创建链接列表的深层副本,我不完全确定它是如何完成的。

Here's a part of my code:这是我的代码的一部分:

class Stack {
    private:
        struct Node  {
           int data;
           Node *next;
       };

        Node *stackTop;

    public:
        Stack() {stackTop = nullptr;}
        Stack(const Stack& original);
        ~Stack();
        bool isEmpty() const;
        int top() const;
        int pop();
        void push(int newItem);
};

Stack::~Stack()   {
        delete stackTop;
}

Stack :: Stack (const Stack& original)   {

// DEEP COPY

}

void list (obj)   {
    cout << "[";
    while(temp -> link != nullptr)
    {
        cout << temp -> data << ",";
        temp = temp -> next;
    }
    cout<< temp -> data << "]" << endl;
    }

I'm trying to implement a stack on the heap using a linked list.我正在尝试使用链表在堆上实现堆栈。

To make a deep copy, simply iterate the list allocating new nodes for the data values in the source list.要进行深层复制,只需迭代列表,为源列表中的data值分配新节点。

for using the 'list' function I need to create a deep copy of the linked list*使用“列表”function 我需要创建链接列表的深层副本*

No, you don't.不,你没有。 A function to display the contents of the stack list should not need to make any copy at all.显示堆栈列表内容的 function 根本不需要进行任何复制。

Try something like this:尝试这样的事情:

class Stack {
private:
    struct Node {
        int data;
        Node *next = nullptr;
        Node(int value) : data(value) {}
    };

    Node *stackTop = nullptr;

public:
    Stack() = default;
    Stack(const Stack& original);
    Stack(Stack &&original);
    ~Stack();

    Stack& operator=(Stack rhs);

    ...

    void list(std::ostream &out) const;
};

Stack::~Stack()
{
    Node *current = stackTop;
    while (current) {
        Node *next = current->next;
        delete current;
        current = next;
    }
}

Stack::Stack(const Stack& original)
    : Stack()
{
    Node **newNode = &stackTop;
    Node *current = original.stackTop;
    while (current) {
        *newNode = new Node(current->data);
        newNode = &((*newNode)->next);
    }
}

Stack::Stack(Stack &&original)
    : Stack()
{
    std::swap(stackTop, original.stackTop);
}

Stack& Stack::operator=(Stack rhs)
{
    std::swap(stackTop, rhs.stackTop);
    return *this;
}

...

void Stack::list(std::ostream &out)
{
    out << "[";
    Node *current = stackTop;
    if (current) {
        out << current->data;
        while (current->next) {
            out << "," << current->data;
            current = current->next;
        }
    }
    out << "]" << endl;
}

void list(const Stack &obj)
{
    obj.list(std::cout);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM