I saw the following Java code used to implement three stack on a single array.
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 }
My question1 is that Line 4 has allocated memory for the variable buffer. Why in Line 9, we still need to allocate new StackNode.
My question2 is: Can the function pop help recollect the used memory?
For example,
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
Note: This question has been modified and includes the pop function.