Note that there are some explanatory texts on larger screens.

plurals
  1. POUse an array to implement three Stack
    primarykey
    data
    text
    <p>I saw the following Java code used to implement three stack on a single array.</p> <pre><code>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 } </code></pre> <p>My question1 is that Line 4 has allocated memory for the variable buffer. Why in Line 9, we still need to allocate new StackNode.</p> <p>My question2 is: Can the function pop help recollect the used memory?</p> <p>For example,</p> <pre><code>Stack1_E1 =&gt; Stack1_E2 =&gt; Stack2_E1 =&gt; Stack2_E2 =&gt; Stack3_E1 </code></pre> <p>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.</p> <p>Is the function pop designed correctly? Thank you</p> <p>Note: This question has been modified and includes the pop function.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload