【问题标题】:2 Stacks In A Single Array Memory Efficiancy单个阵列中的 2 个堆栈内存效率
【发布时间】:2014-11-14 12:26:56
【问题描述】:

这是我遇到的一个竞争性测验问题。而且我对提供的答案不满意。

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) 标记为正确。我错过了什么?

谢谢。

【问题讨论】:

    标签: arrays data-structures stack


    【解决方案1】:

    首先可视化问题。当您从每个堆栈中的几个数据点开始时,您的数组和顶部可能如下所示 (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 是唯一有效的答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-21
      • 1970-01-01
      • 2021-09-22
      • 2014-12-23
      • 2018-08-05
      • 1970-01-01
      • 2021-08-21
      • 1970-01-01
      相关资源
      最近更新 更多