Implementing a stack

Mar 2, 2011 at 2:12pm
Hi I'm new here and I'm also a beginner programmer.

In school I was given a assignment to create a program implementing a stack using an array... I understand the concept of the stack because it was taught in class, but I'm having trouble with the code. I am also a bit rusty on arrays. Any ideas? (C++ is what I'm using, of course)
Mar 2, 2011 at 2:19pm
Are you going to use a fixed-size circular buffer or a dynamically expandable array?
Do you have any code so far?
Mar 2, 2011 at 2:28pm

fixed-size circular buffer or a dynamically expandable array?

No offense, but I doubt a beginner programmer working on a school assignment will have any idea what you're talking about.
Mar 2, 2011 at 2:49pm

fixed-size circular buffer or a dynamically expandable array?


Also no offense intended, but circular buffers are used for queues, not for stacks.
Mar 2, 2011 at 3:08pm
It's not like you couldn't use circular buffers for stacks, it's just not a good idea.
Mar 2, 2011 at 3:57pm
Back to the OP:

As Bazzy asked, do you have any code so far?

A stack needs the following:
- a push function
- a pop function
- a way to tell when the stack is full (so you don't push)
- a way to tell when the stack is empty (so you don't pop)
- a pointer to the top of the stack so you know where to push to or pop from

Because you mentioned arrays, I assume you will be using an standard, fixed-size array to implement your stack. You will need an index counter or a pointer into the array to indicate where the top of the stack is. From that you can determine full and empty. I will leave pushing and popping for you to try implementing for the time being.

As far as being rusty with arrays:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// number of elements in the array
#define ARRAYSIZE (3)

// declare an array of  ints, indexed from 0 to (STACKSIZE - 1)
int array[ARRAYSIZE];

// access the first int in the array
int first = array[0];

// access the last int in the array
int last = array[ARRAYSIZE - 1];

// loop through all of the ints in the array
for (int i = 0; i < ARRAYSIZE; ++i)
{
        int current = array[i];
}


Why don't you start writing a Stack class and show us what you have. We can better help you with difficulties at that point.
Last edited on Mar 2, 2011 at 3:59pm
Mar 3, 2011 at 7:44pm
Thank you so much!

This should be enough to get me started, thank you again this will help me a lot. I will experiment with it and see what I can get done.
Topic archived. No new replies allowed.