Array Implementation of a Stack


In C++, we could implement an array-based stack as a class.

Data members

Member Functions

The example functions described here correspond to the interface of the stack class in the C++ standard library. Variations are certainly possible.

  1. Default constructor

    Sets stack to initial empty state. The stack capacity and stack size should be set to 0. The stack array pointer should be set to nullptr.

  2. size()

    Returns the stack size.

  3. capacity()

    Returns the stack capacity.

  4. empty()

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

  5. clear()

    Sets the stack size back to 0. Does not deallocate any dynamic storage.

  6. top()

    Returns the top item of the stack (stk_array[stk_size - 1]).

  7. push()

    Inserts a new item at the top of the stack.

    procedure push(value: item to insert)
        // If stack is full, reserve additional storage.
        if stk_size == stk_capacity
            if stk_capacity == 0
                reserve(1)
            else
                reserve(stk_capacity * 2)
            end if
        end if
    
        // Insert value into stack array and increment stack size.
        stk_array[stk_size] ← value
        stk_size ← stk_size + 1
    end procedure
    
  8. pop()

    Removes the top item from the stack.

    procedure pop()
        stk_size ← stk_size - 1
    end procedure
    
  9. Copy constructor

    Similar to the copy constructor for the example Vector class in the notes on dynamic storage allocation.

  10. Copy assignment operator

    Similar to the copy assignment operator for the example Vector class in the notes on dynamic storage allocation.

  11. Destructor

    Deletes the stack array.

  12. reserve()

    Reserves additional storage for the stack array.

    procedure reserve(n: amount of storage to reserve)
        if n <= stk_capacity
            return
        end if
        
        Allocate a new array of size n called temp_array
        
        Copy the contents of stk_array into temp_array
        
        stk_capacity ← n
        
        Delete the stk_array
        
        stk_array ← temp_array
    end procedure