Write this as a struct and a class in C++.
struct node { data-type value; node* next; node(data-type value, node* next = nullptr) { this->value = value; this->next = next; } };
Data members
stk_top
- Stack top pointer. Pointer to the top (first) node in the linked list.stk_size
- Number of items currently stored in the stack.Member Functions
Default constructor
Sets stack to initial empty state. The stack top pointer should be set to nullptr
. The stack size should be set to 0.
size()
Returns the stack size.
empty()
Returns true if the stack size is 0; otherwise, false.
clear()
We can easily set the stack back to the empty state by repeatedly calling pop()
until the stack is empty.
top()
Returns the top item of the stack (stk_top->value
).
push()
Inserts a new item at the top of the stack.
procedure push(value: item to insert) Allocate a new stack node, new_node new_node->value ← value new_node->next ← stk_top stk_top ← new_node stk_size ← stk_size + 1 end procedure
pop()
Removes the top item from stack.
procedure pop() delete_node ← stk_top stk_top ← stk_top->next Delete the node delete_node stk_size ← stk_size - 1 end procedure
Copy Constructor
procedure stack(x : reference to a constant stack) // Set the new stack object's list to empty stk_top ← nullptr // Copy the other stack's size stk_size ← x.stk_size // Copy the other stack's linked list clone(x) end procedure
Copy Assignment Operator
procedure operator=(x : reference to a constant stack) if this != &x // Make the left stack object empty clear() // Copy the other stack's size stk_size ← x.stk_size // Copy the other stack's linked list clone(x) end if return *this; end procedure
Destructor
We can delete all of the dynamic storage for the stack by calling the clear()
member function.
clone()
Copies the linked list from the stack x
to this
object.
procedure clone(x : reference to a constant stack) last ← nullptr ptr ← x.stk_top while ptr != nullptr Allocate a new stack node, new_node new_node->value ← ptr->value if last == nullptr stk_top ← new_node else last->next ← new_node; end if last ← new_node ptr ← ptr->next end while end procedure