Advertisement
DevilDaga

Stack

Jul 26th, 2014
279
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.70 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. #define MAX 100
  4.  
  5. typedef struct  
  6. {
  7.     int stack[ MAX ];
  8.     int tos;
  9. }stack_t;
  10.  
  11. void push ( stack_t *p_t, int ele )
  12. {
  13.     if ( p_t->tos   == MAX - 1 )
  14.     {
  15.         printf ( "Stack Overflow.\n" );
  16.         return;
  17.     }
  18.     p_t->stack[ ++p_t->tos ] = ele;
  19. }
  20.  
  21. int isEmpty ( stack_t t )
  22. {
  23.     return ( t.tos == -1 );
  24. }
  25.  
  26. int pop ( stack_t *p_t )
  27. {
  28.     if ( isEmpty ( *p_t ) )
  29.     {
  30.         printf ( "Stack Underflow.\n" );
  31.         return -1;
  32.     }
  33.     return p_t->stack[ p_t->tos-- ];
  34. }
  35.  
  36. int stackTop ( stack_t t )
  37. {
  38.     if ( isEmpty ( t ) )
  39.     {
  40.         printf ( "Stack Empty.\n" );
  41.         return -1;
  42.     }
  43.     return t.stack[ t.tos ];
  44. }
  45.  
  46. void display ( stack_t t )
  47. {
  48.     int i;
  49.     printf ( "STACK:\t" );
  50.     if ( isEmpty ( t ) )
  51.     {
  52.         printf ( "Stack Empty.\n" );
  53.         return;
  54.     }
  55.     for ( i = t.tos; i > -1; i-- )
  56.         printf ( "%6d\t", t.stack[ i ] );
  57.     printf ( "\n" );
  58. }
  59.  
  60. void main ( )
  61. {
  62.     stack_t s;
  63.     int choice, ele;
  64.     s.tos = -1;
  65.     while ( 1 )
  66.     {
  67.         printf ( "1:\tPush\n2:\tPop\n3:\tStack Top\n4:\tDisplay\n0:\tEXIT\nCHOICE:\t" );
  68.         scanf ( "%d", &choice );
  69.         printf ( "\n" );
  70.         if ( !choice )
  71.             break;
  72.         switch ( choice )
  73.         {
  74.         case 1:
  75.             printf ( "Enter element to push:\t" );
  76.             scanf ( "%d", &ele );
  77.             push ( &s, ele );
  78.             display ( s );
  79.             break;
  80.         case 2:
  81.             if ( isEmpty ( s ) )
  82.             {
  83.                 printf ( "Stack Underflow.\n" );
  84.                 continue;
  85.             }
  86.             printf ( "Popped element:\t%d\n", pop ( &s ) );
  87.             display ( s );
  88.             break;
  89.         case 3:
  90.             if ( isEmpty ( s ) )
  91.             {
  92.                 printf ( "Stack Empty.\n" );
  93.                 continue;
  94.             }
  95.             printf ( "Stack Top:\t%d\n", stackTop ( s ) );
  96.             break;
  97.         case 4:
  98.             display ( s );
  99.             break;
  100.         default:
  101.             printf ( "Invalid Input.\nTry Again.\n" );
  102.             continue;
  103.         }
  104.     }
  105.     display ( s );
  106. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement