One implementation is to use an array. Let's say we want to make a stack of ints. We need an array and a seperate variable which marks the top of the stack.
1 2 3
|
const int stacksize = 4;
int array[stacksize];
int top = 0;
|
So we start of with the stack being empty. How do we know? Because top == 0.
Let's push 3 numbers, 8, 3, 5.
Push 8.
1 2
|
array = [8] [?] [?] [?]
top = 1
|
8 is placed in array[top], then top is incremented.
When we push 3, we get:
1 2
|
array = [8] [3] [?] [?]
top = 2
|
And 5:
1 2
|
array = [8] [3] [5] [?]
top = 3
|
Is the stack full? Well, no because top < stacksize.
Let's peek at the top element. Remember, top points to one past the end, so the top element is array[top - 1], which is 5.
Let's pop the stack, that just moves the top of the stack:
1 2
|
array = [8] [3] [5] [?]
top = 2
|
Even though 5 is still there, we ignore it, the top element now holds 3.
I think that covers it. Did you follow that?