检查伪代码

时间:2013-05-05 22:31:08

标签: stack pseudocode pop

Algorithm 1. STACKSTUFF(n)
Input: Integer n
1) Let S = an empty Stack
2) Let X = -1
3) For i = 1 to 2n
4) S.Push(i)
5) End For
6) For i = 1 to n
7) Let X = S.Pop()
8) End For
Output: The contents of X

根据我的理解,S.Push(i)在堆栈S的顶部添加项目i。X = S.Pop()从堆栈S的顶部移除项目并将其分配给X.

然而,我被问到以下问题:

If we assume that n is always > 0, lines 1 to 8 can be replaced by a single line, what would it be?

a) Let X = S.Pop() (It can't be this, since what would be the point in popping a empty stack.)
b) Let X = -1 (Again, this would serve no real point)
c) Let X = n+1 
d) S.Push(n)
e) There is no single line

我的直觉是e,没有单行,但问题是这样表达的方式,如果说有一条线,所以答案必须是c或d(向d学习),但是我无法看到它们中的任何一个如何完成整个算法在一行中所做的事情。有人可以分享他们的意见,任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

X的最终值是什么? 如何确定?
我们在做什么并不重要?
当你弹出一堆N次时会有什么结果?

如果你能回答这些问题,你应该能够找到答案。