栈和队列

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


template<class T>
class Stack
{
private:
	T* _pdata;
	size_t _size;
	size_t _capacity;

public:
	Stack()
		:_pdata(NULL)
		, _size(0)
		, _capacity(0)
	{}

	~Stack()
	{
		if (_pdata != 0)
		{
			delete _pdata;
			_pdata = NULL;
		}
		_size = 0;
		_capacity = 0;
	}

	bool empty()
	{
		if (size == 0)
			return 0;
	}

	size_t size()
	{
		return _size;
	}

	T& top()
	{
		assert(_size);
		return _pdata[size - 1];
	}

	void capacityIsFull()
	{
		if (_size == _capacity)
		{
			size_t new_capacity = _capacity * 2 + 3;
			T* temp = new T[new_capacity];
			for (int i = 0; i < _size; i++)
			{
				temp[i] = _pdata[i];
			}
			delete _pdata;
			_pdata = temp;
			_capacity = new_capacity;
		}
	}

	void push(const T& data)
	{
		capacityIsFull();
		_pdata[_size] = data;
		++_size;
	}

	void pop()
	{
		if (!empty())
		{
			_size--;
		}
		else
		{
			cout << "栈已空" << endl;
		}
	}
}

void FunTest()
{
	Stack<int> s;
	s.push(1);
	s.push(2);
	s.push(3);
	s.push(4);
	s.push(5);
	s.push(6);

	cout << "Stack.size" << s.size() << endl;
	cout << "Stack.top" << s.top() << endl;

	s.pop();
	cout << "Stack.size" << s.size() << endl;
	cout << "Stack.top" << s.top() << endl;

	s.pop();
	cout << "Stack.size" << s.size() << endl;
	cout << "Stack.top" << s.top() << endl;
}


int main()
{
	FunTest();
	return 0;
}
*/

#include<iostream>

 
using namespace std;

template<class T>
struct QueueNode
{
	T _data;
	QueueNode<T>* _next;
	QueueNode(const T& data)
	:_data(data)
	, _next(NULL)
	{}
};

template<class T>
class Queue
{
private:
	Node* _front;
	Node* _rear;
	size_t _size;

public:
	typrdef QueueNode<T> Node;

	Queue()
		:_front(NULL)
		, _rear(NULL)
		, _size(0)
	{}

	~Queue()
	{
		if (_front)
		{
			Node* del = _front;
			_front = _front->_next;
			delete del;
			del = NULL;
		}
	}

	bool empty()
	{
		if (!_front)
			return 0;
	}

	size_t size()
	{
		return _size;
	}

	T& front()
	{
		return _front->_data;
	}

	void push(const T& data)//尾插
	{
		if (empty())
		{
			Node* newnode = new Node(data);
			_front = _rear = data;
			++_size;
		}
		else
		{
			Node* newnode = new Node(data);
			_rear->_next = newnode;
			_rear = _rear->_next;
			++_size;
		}
	}

	void pop()//头删
	{
		if (empty())
			cout << "栈已空" << endl;
		else
		{
			Node* del = _front;
			_front = _front->_next;
			delete del;
			del == NULL;
		}
	}
};

void FunTest()
{
	Queue<int>s;
	s.push(1);
	s.push(2);
	s.push(3);
	s.push(4);
	s.push(5);

	cout << "size" << s.size() << endl;
	cout << "front" << s.front() << endl;

	s.pop();
	cout << "size" << s.size() << endl;
	cout << "front" << s.front() << endl;

}

int main()
{
	FunTest();
	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值