Hanoi汉诺塔非递归栈解

#include<stdio.h>
#include<stdlib.h>
# define MaxSize 3 
typedef struct
{
	int n;
	char x,y,z;
	bool flag;
}ElemType;
typedef struct
{
	ElemType data[MaxSize];
	int top;
}StackType;
void InitStack(StackType *&st);
void DestroyStack(StackType *&s);
bool StackEmpty(StackType *s);
bool Push(StackType  *&s,ElemType e);
bool Pop(StackType *& s,ElemType &e);



void hanoi(int n,char x,char y,char z)
{
	StackType *st;
	ElemType e,e1,e2,e3;
	if(n<=0)return ;
	InitStack(st);
	e.n=n;e.x=x;e.y=y;e.z=z,e.flag=true;
	if(n==1)
	{
		e.flag=false;
	}
	else{
		e.flag=true;
	}
	Push(st,e);
	while(!StackEmpty(st))
	{
		Pop(st,e);
		if(e.flag==false)
		{
			e1.n=e.n-1;
			e1.x=e.y;
			e1.y=e.x;
			e1.z=e.z;
			if(e1.n==1)
			{
				e1.flag=true;
			}
			else{
				e1.flag=false;
			}
			Push(st,e1);
			e2.n=e.n;
			e2.x=e.x;
			e2.y=e.y;
			e2.z=e.z;
			e2.flag=true;
			Push(st,e2);
			e3.n=e.n-1;
			e3.x=e.x;
			e3.y=e.z;
			e3.z=e.y;
			if(e3.n==1)
			{
				e3.flag=true;
			}
			else{
				e3.flag=false;
			}
			Push(st,e3);
		}
		else
			printf("将第%d个盘片从%c移动到%c\n",e.n,e.x,e.z);		
	}
	DestroyStack(st);
}				
void InitStack(StackType *&s)
{
	s=(StackType *)malloc(sizeof(StackType));
	s->top=-1;
} 
void DestroyStack(StackType *&s)
{
	free(s);
}
bool StackEmpty(StackType *s)
{
	return(s->top==-1);
}
bool Push(StackType *&s,ElemType e)
{
	if (s->top==MaxSize-1)    
		return false;
	s->top++;
	s->data[s->top]=e;
	return true;
}
bool Pop(StackType *&s,ElemType &e)
{
	if (s->top==-1)		
		return false;
	e=s->data[s->top];
	s->top--;
	return true;
} 


int main()
{   
	hanoi(3,'x','y','z');
	
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值