现在的位置: 首页 > 综合 > 正文

栈C++模版实现(数组版)

2018年04月29日 ⁄ 综合 ⁄ 共 796字 ⁄ 字号 评论关闭
#include <iostream>
using namespace std;

const unsigned int maxn = 65535;

template<typename T>
class myStack
{
public:
	myStack(): length(0)
	{
		head = bottom = &data[0];
		memset(data, 0, sizeof(data));
	}
	
	void push(const T&);
	void pop();
	T& top();
	bool empty()
	{
		return length == 0;
	}
	unsigned int size()
	{
		return length;
	}
private:
	T data[maxn];
	int *bottom, *head;
	unsigned int length;	
};

template<typename T>
void myStack<T>::push(const T& val)
{
	if(empty())
	{
		*bottom = *head = val;
	}
	else
	{
		*++head = val;
	}
	length++;
}

template<typename T>
T& myStack<T>::top()
{
	return *head;
}

template<typename T>
void myStack<T>::pop()
{
	if(empty())
	{
		cout << "empty" << endl;
		return;
	}
	else
	{
		head--;
	}
	length--;
}

int main(void)
{
	myStack<int> st;
	for(int i = 1; i <= 10; ++i)
	{
		st.push(i);
	}	
	cout << "size: " << st.size() << endl;
	for(int j = 0; j < 10; ++j)
	{
		if(!st.empty())
		{
			cout << st.top() << endl;
			st.pop();
			cout << "size: " << st.size() << endl;
		}
	}
	
	return 0;
}

抱歉!评论已关闭.