汉诺塔

#include <stdio.h>
#include <stdlib.h>


typedef int T;
#define NUM 4

struct stack
{
	int size;
	int index;
	T *head;
};

int init(struct stack *p, int n);
void destroy(struct stack *p);
int get_size(struct stack *p);
int get_index(struct stack *p);
int push(struct stack *p, const T *pt);
int pop_(struct stack *p);
T gettop(struct stack *p);
T pop(struct stack *p);
void move(struct stack *pa, struct stack *pb, struct stack *pc, int n);
void print(struct stack *p);

struct stack a,b,c;

int main()
{
	int i;

	// 1
	init(&a, NUM);
	init(&b, NUM);
	init(&c, NUM);
	for(i=0; i<NUM; i++)
	{
		int x=NUM-i;
		push(&a, &x);
	}
	printf("Start pa :\n");
	print(&a);

	// 2
	move(&a,&b,&c,NUM);
	
	//3
	printf("Result :\n");
	print(&b);

	destroy(&a);
	destroy(&b);
	destroy(&c);
	return 0;
}

//////////////////////////////
int init(struct stack *p, int n)
{
	p->size=n;
	p->index=-1;
	p->head = (T*)malloc(n * sizeof(T));
	if(p->head == NULL)
		return -1;
	else
		return 0;
}

void destroy(struct stack *p)
{
	p->size=0;
	p->index=-1;
	free(p->head);
	p->head = NULL;
}

int get_size(struct stack *p)
{
	return p->size;
}

int get_index(struct stack *p)
{
	return p->index;
}

int push(struct stack *p, const T *pt)
{
	p->index++;
	if(p->index < p->size)
	{
		p->head[p->index] = *pt;
		
	}else
	{
		T *pp;
		pp=(T*)realloc(p->head, 2*p->size*sizeof(T));
		if(pp==NULL)
			return -1;
		p->head = pp;
		p->head[p->index] = *pt;
		

	}
	return 0;
}

int pop_(struct stack *p)
{
	if(p->index<0)
		return -1;
	else
		p->index--;
	return 0;
}

T gettop(struct stack *p)
{
	return p->head[p->index];
}

T pop(struct stack *p)
{
	T t=gettop(p);
	pop_(p);
	return t;
}

// pa -> pb ,using pc
void move(struct stack *pa, struct stack *pb, struct stack *pc, int n)
{
	T t;
	if (n<0)
		return;
	if(n==1)
	{
		t=pop(pa);
		push(pb,&t);

		printf("move %d %x -> %x\n", t, pa, pb);
	}else
	{
		move(pa, pc, pb, n-1);
		t=pop(pa);
		push(pb,&t);
		printf("move %d %x -> %x\n", t, pa, pb);
		move(pc, pb, pa, n-1);
	}
	return;
}
void print(struct stack *p)
{
	int i;
	
	for(i=0; i<p->size; i++)
	{
		
		printf("%d\n", p->head[i]);
	}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值