动态数组实现的Stack类(过渡版)

//-------------DStack.h----------------
#include<iostream>

#ifndef DSTACK
#define DSTACK

typedef int StackElement;

class Stack
{
public:
    Stack(int numElements=128);
	bool empty() const;
	void push(const StackElement & value);
	void display(ostream & out) const;
	StackElement top() const;
	void pop();
private:
	int myTop;
	int myCapacity;
	StackElement *myArray;
	
};
#endif

//------------DStack.cpp------------------
#include<iostream>
#include<cassert>
#include<new>
using namespace std;

#include"DStack.h"

Stack::Stack(int numElements)
{
	assert(numElements>0);
	myCapacity=numElements;

	myArray=new (nothrow) StackElement[myCapacity];
	if(myArray!=0)
		myTop=-1;
	else
	{
		cout<<"Inadequate memory to allocate stack \n";
			exit(1);
	}
}

bool Stack::empty() const
{
	return (myTop==-1);
}

void Stack::push(const StackElement & value)
{
	if(myTop<myCapacity-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";
}


//-------------DStack_main.cpp---------------------
#include<iostream>
using namespace std;

#include"DStack.h"

int main()
{
	Stack s;
	cout<<"Enter second stack's capacity: ";
	int cap;
	cin>>cap;
	Stack s2(cap);
	/*
	//
	//
	//
	                  */
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值