In C++, we could implement an array-based stack as a class.
Data members
stk_array - Stack array pointer. A pointer to the data type of the items stored in the stack; points to the first element of a dynamically-allocated array.stk_capacity - Stack capacity. The number of elements in the stack array.stk_size - Stack size. The number of items currently stored in the stack. The top item in the stack is always located at subscript stk_size - 1.Member Functions
The example functions described here correspond to the interface of the stack class in the C++ standard library. Variations are certainly possible.
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.
size()
Returns the stack size.
empty()
Returns true if the stack size is 0; otherwise, false.
clear()
Sets the stack size back to 0. Does not deallocate any dynamic storage.
top()
Returns the top item of the stack (stk_array[stk_size - 1]).
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
// Insert value into stack array and increment stack size.
stk_array[stk_size] ← value
stk_size ← stk_size + 1
end procedure
pop()
Removes the top item from the stack.
procedure pop()
stk_size ← stk_size - 1
end procedure
Copy constructor
Similar to the copy constructor for the example Vector class in the notes on dynamic storage allocation.
Copy assignment operator
Similar to the copy assignment operator for the example Vector class in the notes on dynamic storage allocation.
Destructor
Deletes the stack array.
reserve()
Reserves additional storage for the stack array.
procedure reserve(n: amount of storage to reserve)
if n < stk_size or 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