////// 模拟 递归函数的调用堆栈 /// /// private void GoHonoi(int n) { Step sp = new Step(n,'A','B','C'); //用栈来模拟系统的 递归调用栈 LinkStack ls = new LinkStack(); int count = 0; //相当于调用 Honoi(n,'A','B','C'); ls.Push(sp); while(!ls.Empty()) { Step topStep = (Step)ls.Top(); while (topStep.n > 1) { //将 Honoi(n-1...)压栈 ls.Push(new Step(topStep.n-1,topStep.A,topStep.C,topStep.B)); topStep = (Step)ls.Top(); } //至此,honoi(n..) 的 递归函数均入栈 if (topStep.n == 1) { textBox3.AppendText(string.Format("{3}:移动 {2} 盘, {0} 到 {1}\n", topStep.A, topStep.C,1,++count)); ls.Pop(); topStep = (Step)ls.Top(); } //如果栈不为空 if (!ls.Empty()) { textBox3.AppendText(string.Format("{3}:移动 {2} 盘, {0} 到 {1}\n", topStep.A, topStep.C, topStep.n, ++count)); ls.Pop(); ls.Push(new Step(topStep.n - 1, topStep.B , topStep.A, topStep.C)); topStep = (Step)ls.Top(); } } }
第一次调用GoHonoi(n)