两种操作都是递归实现,汉诺塔思想。
1、逆序栈
void ReverseStack(Stack& stack) { if (stack.Count == 0) return; object top = stack.Pop(); ReverseStack(stack); if (stack.Count == 0) { stack.Push(top); return; } object top2 = stack.Pop(); ReverseStack(stack); //p1 stack.Push(top); ReverseStack(stack); //p2 stack.Push(top2); }举例:
2、排序栈,利用逆序栈的思想实现
void Sort(Stack& stack) { if (stack.Count == 0) return; object top = stack.Pop(); Sort(stack); if (stack.Count == 0) { stack.Push(top); return; } object top2 = stack.Pop(); if ((int)top > (int)top2) { stack.Push(top); Sort(stack); stack.Push(top2); } else { stack.Push(top2); Sort(stack); stack.Push(top); } }
原文地址:http://blog.csdn.net/a809146548/article/details/44683637