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;
}
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.
for using the 'list' function I need to create a deep copy of the linked 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:
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);
}