动态数组(栈)的实现实例

 
#include <iostream>
#include <assert.h>
using namespace std;

const int initStack = 1;
class Istack
{
public:
	Istack();
	~Istack();
	void push(int i);
	int pop();
	int top();
	bool isEmpty();
	void Disp();
private:
	void Grow();
	int *_arr;
	int _capacity;
	int _top;
	int _point;
};

Istack::Istack():_top(0),_capacity(initStack),_point(0)
{
	_arr = new int[initStack];
}

Istack::~Istack()
{
	delete []_arr;
}

void Istack::Grow()
{
	int *_newArr = new int[2 * _capacity];
	int k;
	for(k=0; k<2*_capacity; k++)
		_newArr[k] = _arr[k];
	_point = k;
	_capacity = 2 * _capacity;
	delete []_arr;
	_arr = _newArr;
}

void Istack::push(int i)
{
	assert(_top <= _capacity);
	if(_top == _capacity)
		Grow();
	_arr[_top] = i;
	++_top;
}

int Istack::pop()
{
	if(_top > 0)
		--_top;
	return _arr[_top];
}

int Istack::top()	
{
	assert(_top>0);
	return _arr[_top - 1];
}

bool Istack::isEmpty()
{
	assert(_top>=0);
	return _top == 0;
}

void Istack::Disp()
{
    int k;
	for(k=0; k<_top; k++)
		cout<<"*****"<<_arr[k]<<"*****"<<endl;
	cout<<"the size of Istack is: "<<_top<<endl;
	
}

int main()
{
	Istack *stackIns = new Istack;
	stackIns->push(5);
	stackIns->push(6);
	cout<<"befor pop"<<endl;
	cout<<"the top is: "<<stackIns->top()<<endl;
	stackIns->Disp();

	cout<<"-----------------------"<<endl;
	cout<<"after pop"<<endl;
	cout<<"pop is: "<<stackIns->pop()<<endl;
	cout<<"the top is: "<<stackIns->top()<<endl;
	stackIns->Disp();
	cout<<"-----------------------"<<endl;
	stackIns->push(7);
	stackIns->push(8);
	cout<<"the top is: "<<stackIns->top()<<endl;
	stackIns->Disp();
	return 0;
}

 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值