Stack Implementation in C++

//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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值