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
- Push
- Pop
- Peek
- isFull
- isEmpty
There are two ways to implement a stack:
- Array Implementation
- Linked List Implementation
Push Operation
Steps for push:
- Check if the stack is full. If full, then throw an error.
- If the stack is not full, increment the top (index) by 1 and point to the available space.
- Add the element to the available space.
- 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;
}