我看到以下的《 Java法》用于在单一阵列上三个阵列。
1 int stackSize = 300;
2 int indexUsed = 0;
3 int[] stackPointer = {-1,-1,-1};
4 StackNode[] buffer = new StackNode[stackSize * 3];
5 void push(int stackNum, int value) {
6 int lastIndex = stackPointer[stackNum];
7 stackPointer[stackNum] = indexUsed;
8 indexUsed++;
9 buffer[stackPointer[stackNum]]=new StackNode(lastIndex,value);
10 }
11 int pop(int stackNum) {
12 int value = buffer[stackPointer[stackNum]].value;
13 int lastIndex = stackPointer[stackNum];
14 stackPointer[stackNum] = buffer[stackPointer[stackNum]].previous;
15 buffer[lastIndex] = null;
16 indexUsed--;
17 return value;
18 }
19 int peek(int stack) { return buffer[stackPointer[stack]].value; }
20 boolean isEmpty(int stackNum) { return stackPointer[stackNum] == -1; }
21
22 class StackNode {
23 public int previous;
24 public int value;
25 public StackNode(int p, int v){
26 value = v;
27 previous = p;
28 }
29 }
我的问题1是,第4行为变数的缓冲分配了记忆。 为什么在第9行,我们仍然需要分配新的StackNode。
我的问题2是:这项职能能否帮助收回旧的记忆?
例如,
Stack1_E1 => Stack1_E2 => Stack2_E1 => Stack2_E2 => Stack3_E1
When we call pop(0) // pop the Stack1 Based on my understanding, the free space used by Stack1_E2 will not be reused next time when we call push.
Is the function pop designed correctly? Thank you
注: 这个问题已经修改,包括民俗功能。