「indexOfTop(int stackNum)」方法如何準確計算給定堆棧號的頂部?C#方法indexOfTop(int stackNum)如何確定堆棧的頂部?
來源:破解編碼訪談189編程問題&解決方案:第3章|堆棧和隊列:3.1 - 描述如何使用單個數組來實現三個堆棧。
class FixedMultiStack
{
private int numberOfStacks = 3;
private int stackCapacity;
private int[] values;
private int[] sizes;
public FixedMultiStack(int stackSize)
{
stackCapacity = stackSize;
values = new int[stackSize * numberOfStacks];
sizes = new int[numberOfStacks];
}
public void push(int stackNum, int value)
{
if (isFull(stackNum)) throw new Exception("Full stack, cannot push.");
/* Increment stack pionter and then update top value. */
sizes[stackNum]++;
values[indexOfTop(stackNum)] = value;
}
public int pop(int stackNum)
{
if (isEmpty(stackNum)) throw new Exception("Empty Stack, nothing to pop.");
int topIndex = indexOfTop(stackNum);
int value = values[topIndex]; //Get Top.
values[topIndex] = 0; //Clear
sizes[stackNum]--; //Shrink
return value;
}
/* Return top element. */
public int peek(int stackNum)
{
if (isEmpty(stackNum)) throw new Exception("Empty Stack, nothing to peek at.");
return values[indexOfTop(stackNum)];
}
public bool isFull(int stackNum)
{
return sizes[stackNum] == stackCapacity;
}
public bool isEmpty(int stackNum)
{
return sizes[stackNum] == 0;
}
/* Returns index of the top of the stack. */
private int indexOfTop(int stackNum)
{
int offset = stackNum * stackCapacity;
int size = sizes[stackNum];
return offset + size - 1;
}*
}
它維護一個int []大小數組,用於跟蹤堆棧的大小。 –