Singly-Linked List Implementation of Stack ADT

Write this as a struct and a class in C++.

Sample struct to represent a stack node

struct node
{
    data-type value;
    node* next;
    
    node(data-type value, node* next = nullptr)
    {
        this->value = value;
        this->next = next;
    }
};

Class to represent a stack

Data members

Member Functions

  1. 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.

  2. size()

    Returns the stack size.

  3. empty()

    Returns true if the stack size is 0; otherwise, false.

  4. clear()

    We can easily set the stack back to the empty state by repeatedly calling pop() until the stack is empty.

  5. top()

    Returns the top item of the stack (stk_top->value).

  6. 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
    
  7. 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
    
  8. 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
    
  9. 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
    
  10. Destructor

    We can delete all of the dynamic storage for the stack by calling the clear() member function.

  11. 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