zoukankan      html  css  js  c++  java
  • 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
    ",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');
    	
    }
    
  • 相关阅读:
    register_shutdown_function
    字节转换
    考虑 PHP 5.0~5.6 各版本兼容性的 cURL 文件上传
    linux--svn checkout
    linux命令
    linux---mysql忘记密码
    array_merge函数的注意事项
    逻辑卷使用记录笔记
    系统设计时关于性能问题处理的几点心得
    SSH防暴力破解脚本
  • 原文地址:https://www.cnblogs.com/AmosAlbert/p/12832360.html
Copyright © 2011-2022 走看看