//Simple implementation
#define STACK_CAPACITY 1000
typedef char el_t; // defines the element type el_t to be char for now
class Stack
{
private: // Private data members are:
el_t el[STACK_CAPACITY]; // el is an array with slots 0 .. STACK_CAPACITY-1
int topIndex; // the index to the top element
public:
Stack(); // constructor for a stack
void push(el_t); // adds c to the top of the stack
void pop(el_t &); // removes top element
char top(el_t &); // returns the top element
bool isEmpty(); // returns true if the stack is empty
~Stack(); // destructor for a stack
};
#include <iostream>
using namespace std;
#include<string>
Stack::Stack() // constructor for a stack
{
topIndex=-1;
}
void Stack::push(el_t elem)
{
if(topIndex<STACK_CAPACITY)
{
topIndex++;
el[topIndex]=elem;
}
else
cout<<"Error: Overflow!"<<endl;
}
void Stack::pop(el_t &elem)
{
if (topIndex>-1)
{
elem=el[topIndex];
topIndex--;
}
else
cout<<"Error: Underflow!"<<endl;
}
char Stack::top(el_t &elem)
{
if(isEmpty())
cout<<"Error: Underflow!"<<endl;
else
elem=el[topIndex];
return elem;
}
bool Stack::isEmpty()
{
if (topIndex==-1)
return true;
else
return false;
}
Stack::~Stack()
{
/* nothing to do*/
}
int main()
{
Stack mystack;
string s;
char b;
cout<<"character string? (end with ^Z to quit)" <<endl; //to inform the user to input string.
while(cin>>s)
{
for(int i=0;i<s.length();i++)
{
mystack.push(s[i]);
}
}
cout<<"character removed from the stack is: "<<endl;
while(!mystack.isEmpty())
{
mystack.pop(b);
cout<<b<<endl;
}
cout<<endl;
system("pause");
return 0;
}
Stack Implementation in C++
最新推荐文章于 2019-08-25 14:31:00 发布