这是我面临的竞争性测验问题。我对提供的答案不满意。
A single array A[1..MAXSIZE] is used to implement two stacks.
The two stacks grow from opposite ends of the array.
Variables top1 and top 2 (top1< top 2)
point to the location of the topmost element in each of the stacks.
If the space is to be used efficiently, the condition for “stack full” is
(a) (top1 = MAXSIZE/2) and (top2 = MAXSIZE/2+1)
(b) top1 + top2 = MAXSIZE
(c) (top1 = MAXSIZE/2) or (top2 = MAXSIZE)
(d) top1 = top2 -1
我的逻辑是从两端开始,因此我接着回答(b)然而测验已将答案(d)标记为正确。我错过了什么?
感谢。
答案 0 :(得分:2)
首先想象问题。当您从每个堆栈中的几个数据点开始时,您的数组和顶部可能如下所示(MAXSIZE = 9
):
t1 = 2
t2 = 6
Array indexes: 1 2 3 4 5 6 7 8 9
Stack Tops: |--t1 t2--------|
当你的阵列中充满了数据t1
而t2
就像这样:
t1 = 3
t2 = 4
Array Indexes: 1 2 3 4 5 6 7 8 9
Stack tops: |-----t1 t2--------------|
现在让我们看看是否有任何答案与我们阵列的状态是否完整一致:
(a)(top1 = MAXSIZE / 2)和(top2 = MAXSIZE / 2 + 1):
3 == 9/2 && 4 == 9/2 + 1
3 == 4 && 4 == 5
False
(b)top1 + top2 = MAXSIZE:
3 + 4 == 9
7 == 9
False
(c)(top1 = MAXSIZE / 2)或(top2 = MAXSIZE):
3 == 9 / 2 || 4 == 9
3 == 4 || 4 == 9
False
(d)top1 = top2 - 1:
3 == 4 - 1
3 == 3
True
D是唯一有效的答案。