From 95890fdb6642ba584c28368126344a44aa69e2f2 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Wed, 24 Jun 2020 10:26:55 -0400 Subject: [PATCH] create copy constructor --- data_structures/stack.h | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/data_structures/stack.h b/data_structures/stack.h index f4b8992e7..3957b4d8d 100644 --- a/data_structures/stack.h +++ b/data_structures/stack.h @@ -34,6 +34,36 @@ class stack { size = 0; } + /** Copy constructor*/ + explicit stack(const stack &other) { + node *newNode, *current, *last; + + /* If stack is no empty, make it empty */ + if (stackTop != NULL) { + stackTop = NULL; + } + if (otherStack.stackTop == NULL) { + stackTop = NULL; + } else { + current = otherStack.stackTop; + stackTop = new node; + stackTop->data = current->data; + stackTop->next = NULL; + last = stackTop; + current = current->next; + /* Copy the remaining stack */ + while (current != NULL) { + newNode = new node; + newNode->data = current->data; + newNode->next = NULL; + last->next = newNode; + last = newNode; + current = current->next; + } + } + size = otherStack.size; + } + /** Destructor */ ~stack() {}