>My main problem is with the stack and push and pop -- I do not understand how they work.
A stack is actually very simple, you have a list of items where only the top item can be accessed. You can push a new item onto the stack, thus creating a new top item, and you can pop the current top off of the stack:
Code:
STACK:
1
2
3
POP:
2
3
PUSH 4:
4
2
3
Here is some simple code implementing a fairly general stack structure, feel free to play around with it to get a feel for the concept:
Code:
#include <stdio.h>
#include <stdlib.h>
#define NULLITEM -1
typedef int item;
struct stack
{
item *st;
size_t size;
size_t n;
};
typedef struct stack STACK;
void st_init ( STACK *s, size_t size )
{
s->n = 0;
s->size = size;
s->st = malloc ( sizeof ( item ) * s->size );
if ( s->st == NULL ) {
fprintf ( stderr, "Error allocating memory\n" );
exit ( EXIT_FAILURE );
}
}
void st_kill ( STACK *s )
{
if ( s->st != NULL )
free ( s->st );
}
int st_empty ( STACK *s )
{
return s->n == 0;
}
void st_push ( STACK *s, item new )
{
if ( s->n == s->size ) {
printf ( "Stack is full\n" );
return;
}
s->st[s->n++] = new;
printf ( "Pushed %d\n", new );
}
item st_pop ( STACK *s )
{
if ( s->n == 0 ) {
printf ( "Stack is empty\n" );
return NULLITEM;
}
return s->st[--s->n];
}
int main ( void )
{
int i;
STACK my_stack = {0};
st_init ( &my_stack, 3 );
for ( i = 0; i < 5; i++ )
st_push ( &my_stack, i );
for ( i = 0; i < 5; i++ ) {
int ret = st_pop ( &my_stack );
if ( ret != NULLITEM )
printf ( "Popped %d\n", ret );
}
st_kill ( &my_stack );
return 0;
}
-Prelude