静态数组实现的Stack类

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值