数据结构_栈

c++类模板实现栈

// 栈.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>

using namespace std;

template<class Type>class Stack
{
public:
	Stack();						//创建一个空栈
	Stack(int size);				//创建一个size大的栈
	~Stack();						//回收一个栈
	bool create(int size);			//实际创建一个size大的栈
	void destroy();					//销毁一个栈
	bool isempty() const;			//是否为空
	bool isfull() const;			//是否为满
	bool pop();						//出栈
	bool pop(Type &item);			//出栈并返回出栈元素
	bool push(Type &item);			//进栈
	bool gettop(Type &item);		//取出栈顶元素
	void display();					//显示栈中所有元素
private:
	Type * stackspace;				//栈空间具体实现
	int top;						//栈顶位置,为-1时栈为空
	int stacksize;					//栈大小,为0时栈未创建空间

};
template<class Type>
Stack<Type>::Stack()
{
	stackspace = NULL;
	stacksize = 0;
	top = -1;
}
template<class Type>
Stack<Type>::Stack(int size)
{
	stackspace = NULL;
	stacksize = 0;
	top = -1;
	create(size);
}
template<class Type>
Stack<Type>::~Stack()
{
	destroy();
}
template<class Type>
bool Stack<Type>::create(int size)
{
	if (stacksize)
		return false;
	if (size < 0)
		return false;
	stackspace = new Type[size];
	if (!stackspace)
		return false;
	stacksize = size;
	top = -1;
	return true;
}
template<class Type>
void Stack<Type>::destroy() 
{
	if (stackspace)
		delete[] stackspace;
	stackspace = NULL;
	stacksize = 0;
	top = -1;
}
template<class Type>
bool Stack<Type>::isempty() const
{
	if (!stacksize)
		return true;
	return top == -1 ? true : false;
}
template<class Type>
bool Stack<Type>::isfull() const
{
	if (!stacksize)
		return true;
	return top == stacksize-1 ?true:false;
}
template<class Type>
bool Stack<Type>::pop()
{
	if (isempty())
		return false;
	top--;
	return true;
}
template<class Type>
bool Stack<Type>::pop(Type & item)
{
	if (isempty())
		return false;
	item = stackspace[top];
	top--;
	return true;
}
template<class Type>
bool Stack<Type>::push(Type & item)
{
	if (!stacksize)
		return false;
	if (isfull())
		return false;
	top++;
	stackspace[top] = item;
	return true;
}
template<class Type>
bool Stack<Type>::gettop(Type & item)
{
	if (isempty())
		return false;
	item = stackspace[top];
	return true;
}
template<class Type>
void Stack<Type>::display()
{
	if (isempty())
		cout << "栈尚未建立!" << endl;
	else
	{
		cout << "栈中元素由栈底到栈顶为:" << endl;
		for (int i = 0; i <= top; i++)
			cout << stackspace[i] << " ";
		cout << endl;
	}
}
int main()
{
	Stack<char> s(10);
	char a[4] = {'q','w','e'};
	s.push(a[0]);
	s.push(a[1]);
	s.push(a[2]);
	s.display();
	s.pop();
	char item;
	s.pop(item);
	cout << item << endl;
	s.display();
	system("pause");
	return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值