Stack is an ordered collection of homogeneous data where the insertion and the deletion operation can only be performed at one end called the Top of the stack (TOS). In stack, two basic operations can be performed namely,
- Push operation
- Pop operation
Push operation:
In order to insert an data in the stack, we use push operation. Using an push operation will insert a data to the top of the stack. If top = max - 1 where max is the size of stack, then the condition is called stack overflow that means the stack is full and no more data can be push into the stack. Hence, in an overflow condition, push operation cannot be performed.After every push operation, the top is incremented by one
Algorithm for Push operation:
Step 1: Start
Step 2: Check if the stack is full or not ? if full, goto Step 3 else goto Step 4
Step 3: Print Stack overflow , and exit
Step 4: Input data to be inserted
Step 5: Stack[Top] <--- data
Step 6: Top = Top +1
Step 7: Stop
C-implementation of Push Operation:
int top=-1,max=5;
int Stack[5];
void Push(int n){
if (top != (max-1)){
printf("Enter data to be inserted: \t");
Stack[top]=n;
top=top+1;
}
else{
printf("Stack Overflow");
exit(1);
}
}
Pop operation:
In order to remove an data from the stack, we use pop operation. In an stack, data cannot be randomly removed, the first element to be removed is the one on the top. Hence, using an pop operation will remove an element from the top of the stack. If top = -1 then this condition is called stack underflow that means the stack is empty.So, during an stack underflow condition, pop operation cannot be performed as there are no elements to be removed.After every pop operation, the top is decremented by one.
Algorithm for Pop operation:
Step 1: Start
Step 2: Check if the stack is empty or not ? if empty, goto Step 3 else goto Step 4
Step 3: Print Stack underflow , and exit
Step 4: Stack[Top] ---> dataStep 5: Top = Top -1
Step 6: Stop
C-implementation of Pop Operation:
int top=-1,max=5;
int Stack[5];
void Push(int n){
if (top != -1){
printf("Enter data removed: \t%d",Stack[top]);
top=top-1;
}
else{
printf("Stack Underflow");
exit(1);
}
}