main()
/* Driver for towers */
{
int n;
printf("\n enter a value for n \n");
scanf("%d",&n);
towers(n,1,2,3);
}
towers(n,i,a,f)
1 final nonrecursive version
/* Moves the top n disks
from peg i to peg f
*/
int n,i,a,f;
{
stack s;
1 allocates storage for s (an instance of type stack)
int done
setstack(&s);
done = FALSE;
while(!done)
{
while (n > 1)
{
s_tack(n,i,a,f,&s);
setvar 1(&n,&i,&a,&f);
}
printf("\n %d -> %d\n",i,f);
if(!empty(&s))
{
restore(&n,&i,&a,&f,&s);
printf("\n %d -> %d\n",i,f);
setvar2(&n,&i,&a,&f);
}
else
done = TRUE;
}
setvar1(pn,pi,pa,pf)
/* Sets n to n - 1 and
interchanges f and a
*/
int *pn,*pi,*pa,*pf;
{
int t;
*pn = *pn - 1;
t = *pf;
*pf = *pa;
*pa = t;
}
setvar2(pn,pi,pa,pf)
/* Sets n to n - 1 and
interchanges a and i
*/
int *pn,*pi,*pa,*pf;
{
int t;
*pn = *pn - 1;
t = *pa;
*pa = *pi;
*pi = t;
}
s_tack(n,i,a,f,ps)
/* Creates a record containing
n, i, a, and f and inserts it
on stack s
*/
int n,i,a,f;
stack *ps;
{
stackrecord newrecord;
newrecord.info.n = n;
newrecord.info.i = i;
newrecord.info.a = a;
newrecord.info.f = f;
push(&newrecord,ps);
}
restore(pn,pi,pa,pf,ps)
/* Removes the top record from
stack s and copies its contents
into n,i,a,f
*/
int *pn,*pi,*pa,*pf;
stack *ps;
{
stackrecord value;
pop(ps,&value);
*pn = value.info.n;
*pi = value.info.i;
*pa = value.info.a