Haven't tested it, but i think this'll work:
Code:
#include <stdio.h>
#include <stdlib.h>
/* The 'class'. */
struct cell {
int disc;
struct cell *next;
};
/* The initializer for 'cell'. */
struct cell *newCell( int d )
{
struct cell *c = malloc( sizeof( struct cell ) );
c->disc = d;
c->next = NULL;
return c;
}
/* The 'list' class. */
struct list {
struct cell *rear;
};
/**
*** Their implementation of 'empty()' appears to be done incorrectly.
*** IMO, a null list would crash their application.
**/
int empty( struct list *l ) { return rear == NULL; }
/* The 'pop' function. */
int *pop( struct list * l )
{
struct cell *c = NULL;
int d = -1;
if( !l ) { perror( "'pop( )' passed NULL list'" ); exit( 0 ); }
if( l->rear )
{
c = l->rear;
l->rear = l->rear->next;
d = c->disc;
free( c );
}
return d;
}
/* The 'push' function. */
void push(int d, struct list *l )
{
struct cell *c;
c = newCell( d );
c->next = l->rear;
l->rear = c;
}
void freeList( struct list *l ) { while( !empty( l ) ) pop( l ); }
typedef int (*oper)(int);
int decr(int a)
{
a--;
if(a<0)
a=2;
return a;
}
int incr(int a)
{
a = (a+1)%3;
return a;
}
int main(void)
{
struct list pegs[3];
int n, curr, p1=1, p2=2, d0,d1,d2, i;
oper incr_decr;
printf("Enter the number of discs: ");
scanf( "%d", &n );
for( i = n; i > 0; i-- )
push( i, pegs[curr] );
incr_decr = n%2 ? decr : incr;
while(1)
{
d0 = pop( pegs[curr] );
printf("Disc %d from %d ", d0, curr );
curr = incr_decr(curr);
printf("to %d.\n", curr );
p1 = incr_decr(p1);
p2 = incr_decr(p2);
if(!empry(pegs[p1]) && !empty(pegs[p2]))
{
d1 = pop( pegs[p1] );
d2 = pop( pegs[p2] );
if(d1 < d2)
{
push( d2, pegs[p2] );
push( d1, pegs[p2] );
printf("Disc %d from %d to %d.\n", d1, p1, p2 );
}
else
{
push( d1, pegs[p1] );
push( d2, pegs[p1] );
printf("Disc %d from %d to %d.\n", d2, p2, p1 );
}
}
else
{
if( empty( pegs[p1] ) && empty( pegs[p2] ) )
break;
if( empty( pegs[p1] ) )
{
d2 = pop( pegs[p2] );
d1 = pop( pegs[p1] );
printf("Disc %d from %d to %d.\n", d2, p2, p1 );
}
else
{
d1 = pop( pegs[p1] );
push( d1, pegs[p2] );
printf("Disc %d from %d to %d.\n", d1, p1, p2 );
}
}
}
return 1;
}
Quzah.