回 帖 发 新 帖 刷新版面

主题:谭浩强早已过35编程年龄

去年刚学C,因为初中玩过汉诺塔,但递归总感觉有点“死”就花了两天想出另一种
  用涵数层层嵌套。下次把它带来

回复列表 (共4个回复)

沙发

期待中...

板凳

用栈可以实现汉诺塔

3 楼

方法多着呢,这有个我想到的几个当中效率最好的:
//////////////////////////////////////////////
//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 楼

强人真多呀!

我来回复

您尚未登录,请登录后再回复。点此登录或注册