using System;
using System.Collections.Generic;
using System.Collections;namespace hanoi
{
class HanoiClass:Stack
{

public HanoiClass(int n)
{

}
public HanoiClass()
{

}
private void hanoi(int n,HanoiClass x,HanoiClass y,HanoiClass z)
{
if(n==1)
move(x,z);
else
{
hanoi(n-1,x,z,y);
move(x,z);
hanoi(n-1,y,x,z);
}
}
private void move(HanoiClass x,HanoiClass z)
{
 
z.Push(x.Pop());
        

}
public static void Main()
{
HanoiClass hanoi1=new HanoiClass(3);
HanoiClass hanoi2=new HanoiClass();
hanoi1.Push(1);
hanoi1.Push(2);
hanoi1.Push(3);
hanoi1.hanoi(hanoi1.Count,hanoi1,new HanoiClass(),hanoi2);
int z=hanoi2.Count;
for(int i=0;i<z;i++)
{
Console.WriteLine(hanoi2.Pop());
}
Console.Read();
}
}
}
把一个栈中的三个数移动到另一个栈.原理同汉诺塔..
上面程序是否正确?
如果正确请给出每步执行过程
不正确请给出正确代码...谢谢

解决方案 »

  1.   


    using System;
    using System.Collections.Generic;
    using System.Text;namespace Hannoi
    {
        class Han //2008 Varrily
        {
            public void Move(int n, char x, char y)
            {
                Console.WriteLine("No.{0} From {1} Move to {2}", n, x, y);
            }
            public void Hannoi(int n, char a, char b, char c)
            {
                if (n == 1)
                {
                    Move(1, a, c);
                }
                else
                {
                    Hannoi(n - 1, a, c, b);
                    Move(n, a, c);
                    Hannoi(n - 1, b, a, c);
                }
            }
        }
        class Program
        {
            static void Main(string[] args)
            {
                int Number;
                Console.Write("Input Disk Number : ");
                Number = Convert.ToInt32(Console.ReadLine());
                Han Result = new Han();
                Result.Hannoi(Number,'A','B','C');
                Console.ReadLine();
            }
        }
    }