You are on page 1of 3

Tower of hanoi non-recursive

#include <iostream>

using namespace std;

struct Node

int n;

char a,b,c;

struct Node* next;

};

struct Node* top;

void push(int n,char a,char b,char c)

struct Node* temp=(struct Node*)malloc(sizeof(struct Node));

temp->a=a;

temp->b=b;

temp->c=c;

temp->n=n;

temp->next=top;

top=temp;

void pop()

struct Node* temp=(struct Node*)malloc(sizeof(struct Node));

if(top==NULL)

return;

temp=top;

top=top->next;

free(temp);
}

int empty()

return(top==NULL)?1:0;

struct Node* Top()

return top;

int main()

int n;

scanf("%d",&n);

push(n,'A','B','C');

while(!empty())

struct Node* temp=Top();

n=temp->n;

char a=temp->a;

char b=temp->b;

char c=temp->c;

pop();

if(n==1)

printf("Move top disk from %c to %c\n",a,c);

else

push(n-1,b,a,c);

push(1,a,b,c);

push(n-1,a,c,b);
}

You might also like