Stacks

It is a linear data structure that follows the Last In First Out principle (that is, it removes the last inserted element first from the top).

Operations of Stacks

  1. Push
  2. Pop
  3. Peek
  4. isFull
  5. isEmpty

There are two ways to implement a stack:

  1. Array Implementation
  2. Linked List Implementation

Push Operation

Steps for push:

  1. Check if the stack is full. If full, then throw an error.
  2. If the stack is not full, increment the top (index) by 1 and point to the available space.
  3. Add the element to the available space.
  4. Return a success
struct Stack{
  int array[3];
  // Starting at -1 since arr index first starts at 0.
  int top{-1};

  Stack()
  {
    for( int i{}; i < 3; ++i )
      stackSize[i] = -1;
  }
};

void push( Stack &, int );

void push( Stack &s, int num )
{
  // Getting length array
  int len = sizeof( s.array ) / sizeof(s.array[0] ) - 1;

  // If the stack is full, throw error.
  if( s.top == len ) {
    std::cout << "Stack is full.\n";
    return;
  }

  // else, increment top by 1, point to available space, and add element to said space.
  ++s.top;
  s.array[s.top] = num;
}