Saturday, 6 August 2016

Stack implementation using C !

Hello guys and girls !
Here is the implementation of Stack using C language .


So, what do I mean by implementation ??
When dealing with data structures I encountered 2-3 terms -
  1. Interface
  2. Implementation 
  3. ADT(Abstract Data Type).   
Normally we can assume that interface is something that we see/ user is allowed to see, implementation is something that is playing role behind the terminal in the source file and such hidden data type is referred as ADT.

I guess this is sufficient to start with STACK .

Stack is an ADT , stack in Data Structures is exactly same as in real life , i.e. we are allowed to add elements on the top only and we can remove the elements from the top only , so as LIFO ( Last in first out ).

In C , Stack can be implemented using array or linked list .
Dealing with array implementation is somewhat simpler for beginner so I would like to start with implement Stack using Array .

We need to declare globally , variable "top" of type int , and array[max].  

There are several standard function of Stack .

Initialize(); 
  • Initializing means assigning -1 to top .
Push();
  • Incrementing top , and assigning the value to array[top].
Pop();
  • Return/print the top most element and decrease top by 1.
Peep();
  • Print the top most element 
Traverse(); 
  • Print the whole stack from top to bottom . 
Now lets look at the code : 


//stack
//implementation using array


#include<stdio.h>
#include<stdlib.h>

#define max 10

void pop();
void push();
void peep();
void traverse();
void initialize();

int stack[max];
int top;

void main()
{
int choice;

while(1){

    printf("\nChoose from the following :");
    printf("\n1.Initialize");
    printf("\n2.Push");
    printf("\n3.Pop");
    printf("\n4.Peep");
    printf("\n5.Traverse");
    printf("\n6.Exit\n");
    scanf("%d",&choice);
    switch(choice)
    {

    case 1:
    initialize();break;
    case 2:
    push();break;
    case 3:
    pop();break;
    case 4:
    peep();break;
    case 5:
    traverse();break;
    case 6:
    return ;
    default :
    printf("Thank you !");
    }
}
}
void initialize()
{
top = -1;
}
void push()
{
if(top==max-1)
    printf("\nStack is full : Overflow\n");
else{
printf("\nEnter an integer:\n");
top++;
scanf("%d",&stack[top]);}
}
void pop()
{
if(top==-1)
    printf("\nStack is empty : Underflow\n");
else{
printf("\npopped element : %d\n",stack[top]);
top--;}
}
void peep()
{
printf("\n%d\n",stack[top]);
}
void traverse()
{
printf("Here is the stack\n");
int i;
for(i=top;i>=0;i--)
printf("%d\n",stack[i]);
}

Thanking you !

1 comment :