2
Algorithm 1. QUEUESTUFF(n)
Input: Integer n
1) Let Q = an empty Queue
2) For i = 1 to n
3) Q.Enqueue(i)
4) End For
5) For i = 1 to n-1
6) Let X = Q.Dequeue()
7) End For
8) Let X = Q.Dequeue()
Output: The contents of X

Q.Enqueue(X) add item X to the queue
X = Q.Dequeue() extracts an item from the queue and assigns it to X. 
If the queue is empty then -999 is returned.

如果 n > 0 我知道这个算法将输出 n-1 例如如果 n = 6,将输出 X 将等于 5。

但是,如果 n < 0 怎么办?循环可以从 1 变为负数吗?如果不是...我相信没有一个 For 循环会运行,给我们一个 -999 的输出(因为队列是空的)。

但是,如果循环可以变成负数,那么假设 n= -2。队列为 {1, 0, -1, -2}。然后我们将不得不出队 1 到 -3 次...使 X(应用出队的最后一项)-2。那么现在这个算法返回了什么?几乎 n=X 正确吗?

4

1 回答 1

0

For n>0 the queue will be filled in the following order (lines 1 to 4):

1, 2, 3, ..., n

in lines 5 to 7 you are extracting one by one (FIFO: first-in first-out):

1, 2, 3, ..., n-1

and finally in line 8 you extract last element:

X = n

Like the algorithm is stated I am pretty sure that the For statement is only executed for n >= 1, but for the case of n < 1 (and a For statement running from 1, 0, -1,..., n) the queue is filled with 1-n+1 = 2+abs(n) values and 1-(n-1)+1 = 3+abs(n) values are extracted in lines 5 to 7, so queue is already empty here. In line 8 a read from the now empty queue will return

X = -999

But as I said I assume For i = 1 to n is not executed at all for n<1, so again line 8 will give (because of empty queue):

X = -999  
于 2013-05-06T21:37:21.903 回答