C++学习笔记1-------实现栈

第一次写博客,本系列主要记录下C++学习过程中编写的代码以及遇到的一些问题
#include <iostream>
using std::cout;
using std::endl;

class Stack
{
public:
	Stack(const int stacksize);
	Stack(const Stack & rhs);
	Stack & operator=(const Stack & rhs);
	~Stack();
	void push(const int & x);
	void pop();
	bool empty();
	bool full();
	int top();

private:
	int _stacksize;
	int *_base;
	int *_top;
};

Stack::Stack(const int stacksize)
: _stacksize(stacksize)
, _base(new int[stacksize]())
, _top(_base-1)
{}

Stack::Stack(const Stack & rhs)
: _stacksize(rhs._stacksize)
, _base(new int[_stacksize]())
, _top(_base-1)
{}

Stack & Stack::operator=(const Stack & rhs)
{
	if(this != &rhs)
	{
		delete [] _base;
		_base = new int[rhs._stacksize]();
		_top = _base - 1;
	}
	return *this;
}

Stack::~Stack()
{
	delete [] _base;
	cout << "~Stack()" << endl;
}

void Stack::push(const int & x)
{
	if((_top - _base) <= (_stacksize-1))
	{
		++(_top);
		*_top = x;
	}else
	{
		cout << "Stack is full" << endl;
	}
}

void Stack::pop()
{
	if((_top - _base) >= 0)
	{
		--_top;
	}else
	{
		cout << "Stack is empty" << endl;
	}
}

bool Stack::full()
{
	if((_top - _base) >= (_stacksize-1))
		return true;
	else
		return false;
}

bool Stack::empty()
{
	if((_top - _base) <= -1)
		return true;
	else
		return false;
}

int Stack::top()
{
	return *_top;
}

void test0()
{
	Stack S(10);
	for(int i = 0; i < 15; ++i)
	{
		if(!S.full())
		{
			S.push(i);
		}
		else
		{
			cout << "full, i = " << i << endl;
			break;
		}
	}
	for(int i = 0; i < 15; ++i)
	{
		if(!S.empty())
		{
			cout << "the " << i << " top element is " << S.top() << endl;
			S.pop();
		}
		else
		{
			cout << "empty, i = " << i << endl;
			break;
		}
	}
}

int main(void)
{
	test0();
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值