shared_ptr使用,構建list

節點類:

/**
link list node
**/


#ifndef NODE__H__
#define NODE__H__


#include <memory>


template<typename T>
class node
{
public:
	T val;
	std::shared_ptr<node> next;
public:
	node()
	{
		next.reset();
	}
	explicit node(const T& t)
	{
		val=t;
		next.reset();
	}
};


#endif

list類:

#ifndef list_h__
#define list_h__

#include "node.h"
#include <memory>

template<typename T>
class list
{
public:
	list()
	{
		head.reset();
		tail.reset();
		node_null.reset();
	}
	void push_back(const T& val)
	{
		if(head==node_null)
		{
			head=std::shared_ptr<node<T> >(new node<T>(val));
			tail=head;
		}
		else
		{
			tail->next=std::shared_ptr<node<T> >(new node<T>(val));
			tail=tail->next;
		}
	}
	T front()
	{
		return *head;
	}
	T back()
	{
		return *tail;
	}
	std::shared_ptr<node<T> >begin()
	{
		return head;
	}
private:
	std::shared_ptr<node<T> > head;
	std::shared_ptr<node<T> > tail;
public:
	std::shared_ptr<node<T> > node_null;
};

#endif


測試:

#include "list.h"
#include "node.h"
#include <iostream>

int main(int argc,char* argv[])
{
	list<int> l;
	l.push_back(23);
	l.push_back(2);
	auto t=l.begin();
	while(t!=l.node_null)
	{
		std::cout<<t->val<<std::endl;
		t=t->next;
	}
	system("PAUSE");
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章