算法来复制一个堆栈 [英] algorithm to copy a stack
本文介绍了算法来复制一个堆栈的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有可能堆栈复制到另一个在C中不使用任何外部堆栈或数组?
Is it possible to copy a stack onto another in C without using any external stack or array?
我知道,它可以使用递归来完成,但是否还有其他可能的解决方案提到限制范围内做到这一点?
I know that it can be done using recursion, but are there any other possible solution to do this within mentioned constraints?
推荐答案
是的,这是可能的,但它是要采取 O(N ^ 2)
。考虑栈取值
(源)和 T
(目标)。
Yes, it is possible, but it is going to take O(N^2)
. Consider stacks S
(source) and T
(target).
- 的init
计数
零 - 在弹出的顶级元素
电子
从堆栈取值
,然后将剩余的数据推入堆栈T
,留下计数
堆栈项取值
- 按
电子
在取值
顶
- 复制元素回程从
T
到取值
- 增量
计数
- 如果计数不等于对
取值
的项目数,请回到步骤1 - 在弹出
取值
的元素和推入T
- init
count
to zero - pop the top element
E
off the stackS
, then push the remaining data onto stackT
, leavingcount
items on stackS
- push
E
on top ofS
- Copy elements back from
T
toS
- increment
count
- If count is not equal the number of items on
S
, go back to step 1 - pop elements of
S
and push ontoT
步骤0至到位5反向堆栈取值
;第6步移动它交给 T
,扭转了订单和生产的原件及复印件。这是一个破坏性的拷贝,但因为原来的堆栈现在是空的。
Steps 0 through 5 reverse stack S
in place; step 6 moves it over to T
, reversing the order and producing a copy of the original. It's a destructive copy, though, because the original stack is now empty.
这篇关于算法来复制一个堆栈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文