第一次写list的实现 要是有不小心错了的地方,请留言改正
创建迭代器类,实质上就是封装一个节点指针,通过节点指针实现操作,至少要实现的操作符已说明。这两个类都要设置List为友元类,因为这样才能用List直接操作迭代器的相关操作。
创建一个类,用来存放list的内容,不过可以用struct来代替,list可以写入初始值的构造和析构
可暂时将迭代器理解成一个指针,该指针指向list中的某个节点
迭代器中的函数用来进行各种基础操作
写的不是很详细,不是很齐全。
所写代码如下
namespace ghc
{
template<class _Ty>
class list;
template<class _Ty>
class List_iterator;
template<class _Ty>
class Node
{
//因为在后面会用到Node,则需要引入友元类
friend class list<_Ty>;
friend class List_iterator<_Ty>;
public:
Node() :_val(_Ty()), _next(nullptr), _prev(nullptr)
{}
Node(const _Ty& val, Node* next = nullptr, Node*prev = nullptr)
:_val(val), _next(next), _prev(prev)
{}
~Node()
{}
private:
Node* _next;
Node* _prev;
_Ty _val;
};
template<class _Ty>
class List_iterator
{
typedef List_iterator<_Ty> self;
public:
List_iterator(Node<_Ty>* _P) :_Ptr(_P)
{}
public:
_Ty& operator*()
{
return _Ptr->_val;
}
self& operator++()//后置++
{
_Ptr = _Ptr->_next;
return *this;
}
self operator++(int)//前置++
{
self tmp(*this);
++*this;
return tmp;
}
self& operator--()
{
_Ptr = _Ptr->_prev;
return *this;
}
bool operator!=(const self& it)
{
return (_Ptr != it._Ptr);
}
Node<_Ty>* _Mynode()
{
return _Ptr;
}
private:
Node<_Ty>* _Ptr;
};
template<class _Ty>
class list
{
public:
typedef List_iterator<_Ty> iterator;
typedef iterator _IT;
public:
//三种构造函数 应对不同的参数
list():_Size(0)
{
CreateHead();
}
list(int n, const _Ty&value = T())
{
CreateHead();
while (--n)
{
insert(begin(), value);
}
}
list(_IT _first, _IT _last)
{
CreateHead();
while (_first != _last)
{
push_back(*_first);
++_first;
}
}
// 拷贝
list<_Ty>& operator=(list<_Ty>& lt)
{
if (this != <)
{
//重新构造一个tmp
list<_Ty> tmp(lt.begin(), lt.end());
swap(_Head, tmp._Head);
}
return *this;
}
~list()
{
clear();
delete _Head;
_Head = nullptr;
}
public:
iterator begin()
{
return iterator(_Head->_next);
}
iterator end()
{
return iterator(_Head);
}
public:// 各个函数的实现
size_t size()const
{
return _Size;
}
bool empty()const
{
return size() == 0;
}
_Ty& front()
{
return *begin();
}
void clear()
{
erase(begin(), end());
}
void swap(list& lt1, list& lt2) //有问题,不会了
{
lt1= lt2;
}
public:
iterator insert(iterator _P, const _Ty &x)
{
Node<_Ty>* _S = new Node<_Ty>(x);
Node<_Ty>* cur = _P._Mynode();
_S->_next = cur;
_S->_prev = cur->_prev;
_S->_next->_prev = _S;
_S->_prev->_next = _S;
_Size++;
return iterator(_S);
}
iterator erase(_IT _P)
{
Node<_Ty>* cur = _P._Mynode();
Node<_Ty>* next_node = cur->_next;
cur->_next->_prev = cur->_prev;
cur->_prev->_next = cur->_next;
delete cur;
_Size--;
return iterator(next_node);
}
iterator erase(_IT _first, _IT _last)
{
while (_first != _last)
{
_first = erase(_first);
}
return _IT(_last);
}
protected:
void CreateHead()
{
_Head = new Node<_Ty>;
_Head->_next = _Head;
_Head->_prev = _Head;
}
private:
Node<_Ty>* _Head;
size_t _Size;
};
}
void main()
{
ghc::list<int> mylist(10, 2);
ghc::list<int> youlist; //list<int> youlist = mylist
youlist = mylist;
ghc::list<int>::iterator it = youlist.begin();
while (it != youlist.end())
{
cout << *it << " ";
++it; //it++
}
cout << endl;
}