您的位置:首页 > 编程语言 > C语言/C++

Stack Implementation in C++

2013-05-31 09:54 239 查看
//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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: