Using a stack seems like overkill, but I assume the purpose of the exercise is to play with a stack?
Make sure you implement every method listed in your interface. That means that you must provide the body of the functions for Stack(), ~Stack(), Stack(int), IsEmpty(), IsFull(), and Top().
The way that your stack is managed is by dynamically allocating an array of
std::
strings. Your constructors should therefore do something like:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
Stack( int max_size )
{
// The maximum number of elements in the stack, in other words:
// The exact length of the array you are using to store elements.
maxStack = max_size;
// Index into the array of the current top of the stack.
// At the moment there are no elements, so the top is one-less-than the first element (element zero).
top = -1;
// Create the array with exactly max_size elements available for use
items = new string[ maxStack ];
}
|
Your default constructor does the same thing, except that you should use a value directly instead of 'max_size' (like 30 or 50).
The destructor must, of course,
delete [] items;
.
The IsEmpty() method checks to see if there are any items in the array. You can know this by checking the value of
top
.
The IsFull() method does something similar, using
top
and
maxStack
to see if there is room for more elements. Remember, 'top' is an
index, but 'maxStack' is a
count. They are different things:
0 1 2 3 4 5
There are six items there. The first is number zero. The second is index 1. And so on. The last one is index 5. Notice how 5 is one less than 6, the number (or count) of items.
I don't know if the interface was given to you or if you created it yourself, but one item of advice is that your Push() method should take a const reference:
|
void Push( const string& newItem );
|
|
void Stack::Push( const string& newItem ) {
|
The application only needs now to create a stack and use it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
int main() {
Stack stack20( 20 ); // my variable here is a stack with room for 20 items
// Push "world!" onto the stack.
stack20.Push( "world!" ); // (Currently, "world!" is on the top.)
// Push "Hello " onto the stack.
stack20.Push( "Hello " ); // (Now "Hello " is on the top, and "world!" is underneath "Hello ".)
// (What does this display? And why?)
cout << stack20.Top();
stack20.Pop();
cout << stack20.Top();
cout << endl;
return 0;
}
|
Now all you have to do is think about the order things go
into the stack, and the order they come
off of the stack. Then think about the order you loop through the characters in a string. If I loop through once to create the stack, then loop through again, can I use that to determine if the string is a palindrome?
Hope this helps.