【问题标题】:Deep copying linked list深拷贝链表
【发布时间】:2019-10-20 09:33:12
【问题描述】:

我正在尝试使用链表在堆上实现堆栈。 但是,为了使用“列表”功能,我需要创建链接列表的深层副本,我不完全确定它是如何完成的。

这是我的代码的一部分:

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

【问题讨论】:

  • 您可能需要在Stack 类中为stackTop 使用公共getter 函数,因为stackTop 是私有的。
  • 使用std::stackstd::vector
  • 请注意,实现的栈在堆上,列表函数应该在 Stack 类之外。如果可以在不使用复制构造函数的情况下显示内容,我很高兴知道如何。

标签: c++ linked-list stack implementation


【解决方案1】:

我正在尝试使用链表在堆上实现堆栈。

要进行深层复制,只需迭代列表,为源列表中的data 值分配新节点。

为了使用“列表”功能,我需要创建链接列表的深层副本*

不,你没有。显示堆栈列表内容的函数根本不需要进行任何复制。

试试这样的:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-10
    • 1970-01-01
    • 2011-06-08
    • 1970-01-01
    • 2018-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多