//-------------Stack.h----------------
#include<iostream>
#ifndef STACK
#define STACK
const int STACK_CAPACITY=128;
typedef int StackElement;
class Stack
{
public:
Stack();
bool empty() const;
void push(const StackElement & value);
void display(ostream & out) const;
StackElement top() const;
void pop();
private:
StackElement myArray[STACK_CAPACITY];
int myTop;
};
#endif
//------------Stack.cpp------------------
#include<iostream>
using namespace std;
#include"Stack.h"
Stack::Stack()
:myTop(-1)
{}
bool Stack::empty() const
{
return (myTop==-1);
}
void Stack::push(const StackElement & value)
{
if(myTop<STACK_CAPACITY-1)
{
myTop++;
myArray[myTop]=value;
}
else
{
cerr<<"***Stack full -- can't add new value ***\n";
exit(1);
}
}
void Stack::display(ostream & out) const
{
for(int i=myTop;i>=0;i--)
out<<myArray[i]<<endl;
}
StackElement Stack::top() const
{
if(!empty())
{
return (myArray[myTop]);
}
else
{
cerr<<"***Stack is empty -- returning garbage value ***"
<<endl;
StackElement garbage;
return garbage;
}
}
void Stack::pop()
{
if(!empty())
myTop--;
else
cerr<<"*** Stack is empty -- can't remove a value ***\n";
}
//-------------Stack_main.cpp---------------------
#include<iostream>
using namespace std;
#include"Stack.h"
int main()
{
Stack s;
cout<<"Stack created. Empty? "<<boolalpha<<s.empty()<<endl;
cout<<"How many elements to add to the stack?";
int numItems;
cin>>numItems;
for(int i=1;i<numItems;i++)
s.push(i);
cout<<"Stack contents:\n";
s.display(cout);
cout<<"Stack empty?"<<s.empty()<<endl;
cout<<"Top value: "<<s.top()<<endl;
while(!s.empty())
{
cout<<"Poping "<<s.top()<<endl;
s.pop();
}
cout<<"Stack empty? "<<s.empty()<<endl;
cout<<"Top value: "<<s.top()<<endl;
cout<<"Trying to pop: "<<endl;
s.pop();
}