漢諾塔非遞迴棧程式碼

likey3發表於2013-02-21
參照遞迴程式碼改編 SETYPE為棧元素{int n,//金片數量 char x,y,z}柱子名稱 棧功能程式碼和輸出程式碼不貼出
初學者   使用純C程式碼
void Hanoi(SETYPE x)
{
    STACK s;
    charc;
    inti = 0 , n =pow(2, x.n) - 1;
  
    AStackCreate(&s);
  
    do
    {
        if(x.n == 1)
        {
            Output(x);
            i ++;
  
            if(!AStackIsEmpty(&s))
            {
                AStackPop(&s, &x);
                Output(x);
                i ++;
                x.n -= 1;
                c = x.y;
                x.y = x.x;
                x.x = c;
            }
        }
        else
        {
            while(x.n != 1)
            {
                AStackPush(&s, x);
                x.n -= 1;
                c = x.y;
                x.y = x.z;
                x.z = c;
            }
        }
          
    }
    while(!AStackIsEmpty(&s) || x.n != 1);
    Output(x);
  
    printf("%d\n", i);
      
    AStackDestroy(&s);
}
 
 

相關文章