肥貓學習日記---------------------Linux下C++使用類模板創建鏈表棧

#include <iostream>

using namespace std;

template <typename T>
class Node
{
public:
	Node(T data):data(data)
	{
		next = NULL;
	}

	T data;
	Node* next;
};

template <typename T>
class Stack
{
	Node<T>* head;
public:
	Stack(void)
	{
		head = NULL;
	}

	bool empty(void)
	{
		return head == NULL;	
	}

	void pop(void)
	{
		Node<T>* temp = head;
		head = head->next;
		delete temp;
	}

	void push(const T& data)
	{
		Node<T>* node = new Node<T>(data);
		node->next = head;
		head = node;
	}

	size_t size(void)
	{
		size_t n = 0;
		for(Node<T>* node=head; node; node=node->next)
		{
			n++;
		}
		return n;
	}

	T& top(void)
	{
		return head->data;
	}
};

int main()
{
	Stack<int> s;
	for(int i=0; i<10; i++)
	{
		s.push(i);
		cout << s.top() << endl;
	}
	cout << "----------" << endl;
	while(!s.empty())
	{
		cout << s.top() << endl;
		s.pop();
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章