Tuesday, July 14, 2009

Data stucture in C with Array Implementation of Stack?

#define __TEST__





#include %26lt;stdio.h%26gt;





#ifdef __TEST__


#include %26lt;conio.h%26gt;


#include %26lt;stdlib.h%26gt;


#endif


#define STACKSIZE 64








int stack[STACKSIZE];


static int stack_ptr=0;





void overflow_test( int pos )


{


if( pos %26gt;= STACKSIZE )


{


puts( "Stack overflow!\n" );


exit(1);


}


}





void underflow_test( int pos )


{


if( pos %26lt; 0 )


{


puts( "Stack underflow!\n" );


exit(1);


}


}





void push( int value )


{


overflow_test( stack_ptr+1 );


stack[stack_ptr++] = value;


}





int pop( void )


{


underflow_test( --stack_ptr );


return stack[stack_ptr];


}





#ifdef __TEST__





void wait4keypress( void )


{


while( !kbhit())


;


}





int main( void )


{


atexit(wait4keypress);


push(1);


push(2);


push(3);


printf( "%d\n", pop());


printf( "%d\n", pop());


printf( "%d\n", pop());


/* must cause stack underflow */


printf( "%d\n", pop());


return 0;


}





#endif /* __TEST__ */


No comments:

Post a Comment