主题:谭浩强早已过35编程年龄
易辕
[专家分:0] 发布于 2006-03-23 20:23:00
去年刚学C,因为初中玩过汉诺塔,但递归总感觉有点“死”就花了两天想出另一种
用涵数层层嵌套。下次把它带来
回复列表 (共4个回复)
沙发
ctjaion [专家分:510] 发布于 2006-04-10 21:05:00
期待中...
板凳
joulejcc [专家分:310] 发布于 2007-03-10 14:03:00
用栈可以实现汉诺塔
3 楼
freeeerf [专家分:5440] 发布于 2007-03-12 19:07:00
方法多着呢,这有个我想到的几个当中效率最好的:
//////////////////////////////////////////////
//This program only programmed for VC which use
//four bits to denote an int type number.
/////////////////////////////////////////////
#include<stdio.h>
#include<time.h>
#define N 20
typedef struct Stack
{
unsigned int n;
struct Stack *next;
}STACK;
void Init(STACK **p)
{
*p=(STACK *)malloc(sizeof(STACK));
(*p)->next=NULL;
}
void Push(STACK *p,unsigned int a)
{
STACK *temp;
temp=(STACK *)malloc(sizeof(STACK));
temp->n=a;
temp->next=p->next;
p->next=temp;
}
unsigned int Pop(STACK *p)
{
STACK *temp;
unsigned int msg;
if(p->next==NULL)
{
puts("Pop error: empty");
system("pause");
exit(1);
}
temp=p->next;
p->next=temp->next;
msg=temp->n;
free(temp);
return msg;
}
int main()
{
STACK *p;
unsigned int a=0x01020300,b;
clock_t t1,t2;
t1=clock();
a+=N;
Init(&p);
while((a&0x000000FF)!=0||p->next!=NULL)
{
while((a&0x000000FF)!=0)
{
Push(p,a);
--a;
b=a; //chang the second bit and the third bit.
a&=0xFF0000FF;
a+=((b&0x0000FF00)<<8);
a+=((b&0x00FF0000)>>8);
}
a=Pop(p);
//printf("%d->%d ",(a&0xFF000000)>>24,(a&0x0000FF00)>>8);
if(((--a)&0xFFFFFF00)>0)
{
b=a;
a&=0x0000FFFF;
a+=((b&0x00FF0000)<<8);
a+=((b&0xFF000000)>>8);
}
}
t2=clock();
printf("\nFor N=%d\nUsing time %.3f\n",N,(float)(t2-t1)/1000);
system("pause");
return 0;
}
4 楼
IT浪子 [专家分:180] 发布于 2007-03-12 22:12:00
强人真多呀!
我来回复