I have a question considering a program that stimulates a stack (not using any built-in stack features or such).
stack2= 1 2 3 4 5 //single dimension array of 5 elements
By calling the method pop the stack should look like the following, basically taking an element off each time the stack is being called up again.
stack2= 1 2 3 4 0
stack2= 1 2 3 0 0
stack2= 1 2 0 0 0
stack2= 1 0 0 0 0
stack2= 0 0 0 0 0
Here is my code:
for (int i = 1; i <= 6; i++)
{
number= TryPop(s2);
//use number
ShowStack(s2, "s2");
}
public void Push(int g)
{
if (top == Max)
{
throw new Exception("Stack overflow...");
}
else
{
tabel[top] = g;
top++;
}
}/*Push*/
I already have code that fills my array with values (through a push method). The pop method should take the last value and place it on 0, then calls up the next stack and place the following on 0 (like shown above in stack2).
The current pop method that keeps track of the top index (0 elements = 0 top, 1 element = 1 top etc..) already includes an underflow warning if this goes on 0 or below (which is correct).
public int Pop()
{
if(top <= 0)
{
throw new Exception("Stack underflow...");
}
else
{
for (int j = tabel.Length - 1; j >= 0; j--)
{
//...Really not sure what to do here.
}
}
return number;
}/*Pop*/
Since in the other class I already have a loop (for loop shown above) that simulates 6 times the s2 stack. (first stack: 1 2 3 4 0, second stack 1 2 3 0 0 and so on.)
How exactly do I take an element off each time? Either I have the entire display on 0 or the 0 in the wrong places / out of index errors.
Edit: Working Pop method:
public int Pop()
{
if(top <= 0)
{
throw new Exception("Stack underflow...");
}
top--;
tabel[top] = 0;
number = tabel[top];
return number;
}/*Pop*/
To implement a stack, you need an array and a “pointer” to the top of the stack.
In your code,
tableis the array andtopis the pointer (as array index).Push
To push an item to a stack, put the item at top of the stack and advance the pointer by one:
That’s what your code already does:
Pop
To pop an item, move the pointer back by one and return+erase the item at the top:
Now try to translate your solution for Push to do the reverse as shown here!