0% found this document useful (0 votes)
46 views3 pages

Tower of Hanoi Non-Recursive

This C++ program implements a non-recursive solution to the Tower of Hanoi problem using a stack data structure. It defines a Node struct to store the disk number, source peg, destination peg, and next node. A stack is implemented using a top pointer to the first Node. Functions are included to push/pop Nodes to/from the stack and check if it is empty. The main function takes user input for the number of disks, pushes the initial state to the stack, and then pops and prints moves until the stack is empty, simulating the non-recursive Tower of Hanoi solution.

Uploaded by

Mithila Arman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views3 pages

Tower of Hanoi Non-Recursive

This C++ program implements a non-recursive solution to the Tower of Hanoi problem using a stack data structure. It defines a Node struct to store the disk number, source peg, destination peg, and next node. A stack is implemented using a top pointer to the first Node. Functions are included to push/pop Nodes to/from the stack and check if it is empty. The main function takes user input for the number of disks, pushes the initial state to the stack, and then pops and prints moves until the stack is empty, simulating the non-recursive Tower of Hanoi solution.

Uploaded by

Mithila Arman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 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