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.
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;
}
To make a deep copy, simply iterate the list allocating new nodes for the
data
values in the source list.No, you don't. A function to display the contents of the stack list should not need to make any copy at all.
Try something like this: