码迷,mamicode.com
首页 > 其他好文 > 详细

递归与非递归(栈实现)实现汉诺塔问题

时间:2021-03-30 13:06:36      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:amp   rom   ret   top   code   from   malloc   lse   str   

include<stdlib.h>

#include<stdio.h>

void Move(char now, int a, char next)
{
	printf("%d:%c->%c\n", a, now, next);
}

void Hanoi(int n, char x, char y, char z)
{
	if (n == 1) Move(x, 1, z);
	else
	{
		Hanoi(n - 1, x, z, y);
		Move(x, n, z);
		Hanoi(n - 1, y, x, z);
	}

}





typedef struct
{
	int n;
	char x, y, z;
}Func;

void move(char from, int n, char to)
{
	printf("%3d:%c->%c\n", n, from, to);
}

typedef Func ElemType;

typedef struct
{
	ElemType* base;
	int top;
	int SatckSize;
}Stack;
typedef Stack* PStack;


void InitStack(PStack S, int size);
bool Pop(PStack S, ElemType* PopItem);
bool Push(PStack S, ElemType PushItem);
ElemType GetTop(PStack S, ElemType* TopItem);
bool IsEmpty(PStack S);




void Hanoi3(int n, char x, char y, char z)
{
	PStack S = (PStack)malloc(sizeof(Stack));
	InitStack(S, 10);
	Func e;
	char t;
	e.n = n; e.x = x; e.y =y; e.z = z; Push(S, e);
	while (1)
	{
		//GetTop(S, &e);
		while (e.n>1)
		{
			e.n--; t = e.y; e.y = e.z; e.z = t;
			Push(S, e);
			GetTop(S, &e);
		}
		Pop(S, &e);
		move(e.x, e.n, e.z);
		if (IsEmpty(S)) return;
		Pop(S, &e);
		move(e.x, e.n, e.z);
		e.n--; t = e.x; e.x = e.y; e.y = t;
		Push(S, e);
	}
}


int main()
{
	char x=‘x‘, y=‘y‘, z=‘z‘;
	Hanoi3(3, x, y, z);
}
void InitStack(PStack S, int size)
{
	if (!S) exit(1);
	if (size > 0) S->base = (ElemType*)malloc(sizeof(ElemType) * size);
	if (!S->base)exit(1);
	S->SatckSize = size;
	S->top = 0;
}
bool Push(PStack S, ElemType PushItem)
{
	if (S->top >= S->SatckSize)
	{
		printf("Stack is full\n"); return false;
	}
	*(S->base + S->top) = PushItem;
	S->top++;
	return true;
}
ElemType GetTop(PStack S, ElemType* TopItem)
{
	if (S->top <= 0)
	{
		printf("NO Item\n");
		exit(1);
	}
	*TopItem = *(S->base + S->top - 1);
	return *TopItem;
}
bool IsEmpty(PStack S)
{
	if (S->top == 0) return true;
	else return false;
}
bool Pop(PStack S, ElemType* PopItem)
{
	if (S->top <= 0)
	{
		printf("Stack is empty\n"); return false;
	}
	S->top--;
	*PopItem = *(S->base + S->top);
	return true;
}

递归与非递归(栈实现)实现汉诺塔问题

标签:amp   rom   ret   top   code   from   malloc   lse   str   

原文地址:https://www.cnblogs.com/tzp-empty-hya/p/14589301.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!