Page 80 - DCAP605_ADVANCED_DATA_STRUCTURE_AND_ALGORITHMS
P. 80

Unit 3: Stacks





             if(Isempty()) print(“statement is parenthetically balanced”);                      Notes
             else print(“statement is parenthetically unbalanced”);
             }



             Lab Exercise
               1.   The program given below implements the stack data structure using an array. In this
                    program the elements are pushed into array stack[ ] through push( ) function. The
                    parameters passed to push( ) are the base address of the array, the position in the
                    stack at which the element is to be placed and the element itself. Care is taken by the
                    push( ) function that the user does not try to place the element beyond the bounds of
                    the stack. This is done by checking the value stored in pos. pop( ) function pops out
                    the last element stored in the stack[ ], because, pos holds the position which has the
                    last element in the stack.

                    /* To pop and push items in a stack */
                    #define MAX 10
                    void push ( int ) ;
                    int pop( ) ;
                    int stack[MAX] ;
                    int pos ;
                    void main( )
                    {
                    int n ;
                      clrscr( ) ;
                    pos = -1 ; /* stack is empty */
                    push ( 10 ) ;
                    push ( 20 ) ;
                    push ( 30 ) ;
                    push ( 40 ) ;
                    n = pop( ) ;
                    printf ( “\nitem popped out is : %d”, n ) ;
                    n = pop( ) ;
                    printf ( “\nitem popped out is : %d”, n ) ;
                    }
                    /* pushes item on the stack */
                    void push ( int data )
                    {
                    if ( pos == MAX - 1 )
                    printf ( “\nStack is full” ) ;
                    else
                    {
                    pos++ ;
                    stack[ pos ] = data ;
                    }



                                           LOVELY PROFESSIONAL UNIVERSITY                                    75
   75   76   77   78   79   80   81   82   83   84   85