STL-模拟实现List

在STL中的List并不单单只是一个链表,其结构设计特别精妙。
简单来说,其结构为: 一个带头结点的双向循环链表
STL-模拟实现List_第1张图片
     主要代码实现:
     
#include 
#include 

using namespace std;


template
struct ListNode
{
	ListNode* _next;
	ListNode* _prev;
	T _data;

	ListNode(const T& x)
		:_data(x)
		, _next(NULL)
		, _prev(NULL)
	{}
};

template  //迭代器
struct ListIterator
{

	typedef ListNode Node;
	typedef ListIterator Self;

	Node* _node;

	ListIterator(){}
	ListIterator(Node* node)
		:_node(node)
	{}

	bool operator!=(const Self& s)
	{
		return _node != s._node;
	}

	Ref operator*()
	{
		return _node->_data;
	}

	Ptr operator->()
	{
		return &(_node->_data);
	}

	Self& operator++()
	{
		_node = _node->_next;
		return *this;
	}

	Self operator++(int)
	{
		Self tmp(*this);
		_node = _node->_next;
		return tmp;
	}

	Self& operator--()
	{
		_node = _node->_prev;
		return *this;
	}

	Self operator--(int)
	{
		Self tmp(*this);
		_node = _node->_prev;
		return tmp;
	}
};


template
class List
{
	typedef ListNode Node;
public:
	typedef ListIterator Iterator;
	typedef ListIterator ConstIterator;
public:
	List()
		:_head(BuyNewNode(T()))
	{
		_head->_next = _head;
		_head->_prev = _head;
	}
	~List()
	{
		Node* tmp = _head->_next;

		while (tmp != _head)
		{
			delete tmp->_prev;
			tmp=tmp->_next;
		}
		_head = NULL;
	}

	void PushBack(const T& x)
	{
		//Node* tmp = BuyNewNode(x);

		//_head->_prev->_next = tmp;
		//tmp->_prev = _head->_prev;

		//_head->_prev= tmp;
		//tmp->_next = _head;

		Insert(End(),x);
	}

	void PopBack()
	{
		Erase(--End());
	}

	void PushFront(const T& x)
	{
		Insert(Begin(), x);
	}

	void PopFront()
	{
		Erase(Begin());
	}

	Iterator Insert(Iterator pos, const T& x)
	{
		assert(pos._node);

		Node* cur = pos._node;
		Node* prev = cur->_prev;

		Node* tmp = BuyNewNode(x);

		prev->_next = tmp;
		tmp->_prev = prev;

		tmp->_next = cur;
		cur->_prev = tmp;

		return tmp;
	}

	Iterator Erase(Iterator pos)
	{
		assert(pos._node && pos._node != _head);

		Node* cur = pos._node;
		Node* prev = cur->_prev;
		Node* next = cur->_next;

		prev->_next = next;
		next->_prev = prev;

		delete cur;
		cur = NULL;

		return next;
	}

	Iterator Begin()
	{
		//return Iterator(_head->_next);
		return _head->_next;
	}

	Iterator End()
	{
		return Iterator(_head);
	}

	ConstIterator Begin()const
	{
		return ConstIterator(_head->_next);
	}

	ConstIterator End()const
	{
		return ConstIterator(_head);
	}
protected:
	Node* _head;

private:
	Node* BuyNewNode(const T& x)
	{
		//次处应该是空间配置器
		return new Node(x);
	}
};

你可能感兴趣的:(STL)