Click on main2.c to get source.
/* File: CExamples/OO_pgm_in_C_new/main2.c */
/* See also: ../C++Examples/Stacks/ for the C++ version
../JavaExampels/Stacks/ for the Java version
*/
#include <stdio.h>
#include "stack_with_delete.h"
extern const stack empty_arr_stack; /* imported empty stack of
array data structure */
extern const stack empty_list_stack; /* imported empty stack of
list data structure */
extern stackptr new_arr_stack(void); /* declare constructor */
/* simply returns (*empty_arr_stack.clone)(&empty_arr_stack) */
/* generic printstack */
void print_stack(stack s)
/* print the stack; note that this function should work
independently of the underlying data structure, i.e.,
it is a generic function */
{stackptr s2ptr; /* store the popped elements */
int i;
s2ptr = (*s.clone)(&s );
printf("Stack contents: ");
while( !(*s2ptr->is_empty)(s2ptr) )
{i = (*s2ptr->pop)(s2ptr);
printf("%2d ", i);
};
printf(" bottom\n"); fflush(stdout);
(*s2ptr->delete_stack)(s2ptr);
}/* end print_stack */
int main(void)
/* Test the stack */
/* Note: this function can use several stack data structures,
and a generic print_stack(stack) function */
{int i;
stackptr sptr;
/* make a new empty stack of a certain data structure */
sptr = (*empty_arr_stack.clone)(&empty_arr_stack);
print_stack( *sptr );
for (i=1; i < 6; i++)
{ printf("Pushing %d \n", i);
(*sptr->push)( i, sptr );
print_stack( *sptr );
}
for (i=0; i < 3; i++)
{ printf("Popping %d \n",
(*sptr->pop)( sptr ) );
print_stack( *sptr );
}
(*sptr->delete_stack)(sptr);
/* use array constructor function */
sptr = new_arr_stack();
printf("Pushing %d \n", 17); (*sptr->push)( 17, sptr );
print_stack( *sptr );
printf("Pushing %d \n", 18); (*sptr->push)( 18, sptr );
print_stack( *sptr );
(*sptr->delete_stack)(sptr);
/* use list empty stack object */
sptr = (*empty_list_stack.clone)(&empty_list_stack);
print_stack( *sptr );
for (i=20; i < 26; i++)
{ printf("Pushing %d \n", i);
(*sptr->push)( i, sptr );
print_stack( *sptr );
}
for (i=0; i < 3; i++)
{ printf("Popping %d \n",
(*sptr->pop)( sptr ) );
print_stack( *sptr );
}
(*sptr->delete_stack)(sptr);
/* use unknown data structure, determined at link time */
/* for make use command line variable NEWSTACK=newstack_<ds> */
/* to specify which newstack_<ds>.o to link */
sptr = new_stack();
print_stack( *sptr );
for (i=30; i < 36; i++)
{ printf("Pushing %d \n", i);
(*sptr->push)( i, sptr );
print_stack( *sptr );
}
for (i=0; i < 3; i++)
{ printf("Popping %d \n",
(*sptr->pop)( sptr ) );
print_stack( *sptr );
}
(*sptr->delete_stack)(sptr);
return 0;
}/* end main */