[英]Deep copying linked list
我正在嘗試使用鏈表在堆上實現堆棧。 但是,為了使用“列表”function,我需要創建鏈接列表的深層副本,我不完全確定它是如何完成的。
這是我的代碼的一部分:
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;
}
我正在嘗試使用鏈表在堆上實現堆棧。
要進行深層復制,只需迭代列表,為源列表中的data
值分配新節點。
使用“列表”function 我需要創建鏈接列表的深層副本*
不,你沒有。 顯示堆棧列表內容的 function 根本不需要進行任何復制。
嘗試這樣的事情:
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.