Saturday, 5 October 2013

Stack implementation in array

 Stack is a data structure in which addition of new element (PUSH operation) or deletion (POP operation)
of an existing element always takes place at the same END. This end is often known as TOP of stack.

stack use First in First Out principal . i.e. each new element inserted at end of list (i.e. at TOP). & deletion also occurred ot end of  List (i.e at TOP).


C code ::


 // stack implementation in array  
 #include<stdio.h>  
 #include<malloc.h>  
 main()  
 {  
      int size,i;  
      int top;  
      printf("\n Inetr MAX size of stack :");  
      scanf("%d",&size);  
           int *arr;  
        arr=(int *) malloc(size * sizeof(int)); // creating arr of given size dynamicaly  
      top=-1;         // intialise top to -1   
      for(i=0;i<size-3;i++) // taking input  
      {  
           printf("\n Inter %d th element of stack :",i+1);  
           push(arr,&top,size); // calling push funtion stack  
      }  
      display(arr,&top);  
      operation(arr,&top,size);  
 }  
 int operation(int *s,int *top,int size)//give menu to do operation;  
 {  
      int n;  
      printf("\n \tinsert ....\n\t 1 for insertion \n\t 2 for deletion \n\t\t ::::");  
      scanf("%d",&n);  
      switch(n)  
      {  
           case 1:  
                push(s,top,size);  
                operation(s,top,size);  
                break;  
           case 2:  
                     pop(s,top);  
                     operation(s,top,size);  
                     break;  
           default:  
                printf("\n u enetr wrong keyword :: enter again");  
                operation(s,top,size);  
                break;  
      }  
 }  
 int push(int *s,int *top,int size)// inserting data to arr  
 {  
      if(*top>=size)  //to check arr is full or not  
      { printf("\n overflow condition");  
      }  
      else  
      *top=*top+1; //increamenting top  
      printf("\n input no to be inserted \n");  
      scanf("%d",(s + *top));// taking input to at arr[top]  
      display(s,top);  
 }  
 int pop(int *s,int *top) // for delete operation on stack  
 {  
      if(*top==-1) // check list is empty or not  
      {  
           printf("\n underflow condition \n");  
      }  
      else   
      *top=*top-1;    // decrementing top  
      display(s,top);  
 }  
 int display(int *s,int *top)  
 {  
      int i;  
      printf("\n data of stack are == :\n");  
      for(i=0;i<=*top;i++)  
       printf("  %d ", *(s+i));  
 }  

OUTPUT :-

No comments:

Post a comment

THANKS FOR UR GREAT COMMENT

Blogger Widgets