Stack implementation using C++
Track completion, mastery, and revision.
Stack implementation
As we have discussed earlier, Stacks are linear data structures and follow mainly two operations, Push & Pop. Addition in a stack is called Push and removal of an entity from the stack is called Pop.
Once we know the details of stack operations, we can understand its implementation in C++ as well. Let’s look at the algorithms for various operations in Stack.
Algorithm for Pushing an item in Stack
Pushing or inserting an element in a stack involves shifting of elements as the new element can be inserted at the top only. In case of the stack being Full and no new element can be inserted, the condition is called Overflow.
/* assume that stack can hold a max of N elements*/
top = -1
read item /*item to be pushed */
If(top == N - 1) then
{
print“ overflow!!!” /*if top is end of the array */
}
Else
{
top = top + 1 /*increment top to make new item hold top position */
}
EndAlgorithm for Popping an item from Stack
Popping or deletion of an entity from a stack will remove the topmost element of the stack. In a case where there is no item in the stack (stack is empty) making removal of item impossible, the condition is called Underflow.
If top == -1 then
{
}
Else
{
}
EndProgram for addition and deletion in a stack
#include <iostream.h>
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX 100 //maximum length of stack
char stack[MAX]; //declaring array as global variable
int top;
void push(char stack[], char value, int& top); //add stack
void pop(char stack[], int& top); //delete stack
void show_Stack(char stack[], int top); //show stack
void main()
{
}
//to add item in the stack
void push(char stack[], char value, int& top)
{
}
//to delete an item from stack
char pop(char stack[], int& top)
{
}
//to show items of stack
void show_Stack(char stack[], int top)
{
}Finished reading?