2014-09-19 87 views
1

这是我遇到的一个竞争性测验问题。我对所提供的答案并不满意。2个堆栈在单个阵列内存中效率

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 

我的逻辑是在两端开始,因此,我的答案(二)但是测验标志着答案(d)为正确去了。我错过了什么?

谢谢。

回答

2

首先看到问题。当你开始在每几个数据点叠加阵列,并且顶部可能看起来像这样(MAXSIZE = 9):

t1 = 2 
t2 = 6 
Array indexes: 1 2 3 4 5 6 7 8 9 
Stack Tops: |--t1   t2--------| 

,当你阵是完整的数据t1t2将是紧挨彼此像这样:

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是唯一可行的答案。

+2

精确到点。谢谢。 – 2014-09-19 20:40:57