#pragma once
#include<iostream>
#include<assert.h>
using namespace std;
namespace zwh
{
template<class T>
struct __list_node
{
T _data;
__list_node<T>* _next;
__list_node<T>* _prev;
__list_node(const T& x = T())
:_data(x)
,_next(nullptr)
,_prev(nullptr)
{}
};
template<class T,class Ref, class Ptr>
struct __list_iterator
{
typedef __list_node<T> node;
typedef __list_iterator<T, Ref, Ptr> self;
node* _node;
__list_iterator(node* node)
:_node(node)
{}
bool operator!=(const self& s) cosnt
{
return _node != s._node;
}
bool operator==(const self& s) const
{
return !(*this != s);
}
T& operator*()
{
return _node->_data;
}
self& operator++()
{
_node = _node->next;
return *this;
}
self operatpr++(int)
{
self tmp(*this);
_node = _node->next;
return tmp;
}
self& operatpr--()
{
_node = _node->prev;
return *this;
}
self operatpr--(int)
{
self tmp(*this);
_node = _node->prev;
return tmp;
}
};
template<class T>
class list
{
typedef __list_node<T> node;
public:
typedef __list_iterator <T, T&, T*> iterator;
typedef __list_iterator <T, const T&, const T*> const_iterator;
iterator begin()
{
return _head->_next;
}
iterator end()
{
return _head;
}
const_iterator begin() const
{
return _head->next;
}
const_iterator end() const
{
return _head;
}
list()
{
_head = new node;
_head->_prev = _head;
_head->_next = _head;
}
template<class InputIterator>
list(InputIterator first, InputIterator last)
{
_head = new node;
_head->_next = _head;
_head->_prev = _head;
while (first != last)
{
push_back(*first);
++first;
}
}
list(const list<T>& lt)
{
_head = new node;
_head->_next = _head;
_head->_prev = _head;
list<T> tmp(lt.begin(), lt.end());
swap(_head, tmp._head);
}
list<T>& operator=(list<T> lt)
{
swap(_head, lt._head);
return *this;
}
void push_back(const T& x)
{
node* newnode = new node(x);
node* tail = newnode->_prev;
tail->_next = newnode;
head->_prev = newnode;
newnode->_prev = tail;
newnode->_next = _head;
}
iterator insert(iterator pos, const T& x)
{
iterator newnode = new node(x);
iterator cur = pos._node;
iterator prev = cur->_prev;
prev->_next = newnode;
newnode->_prev = prev;
newnode->_next = cur;
cur->_prev = newnode;
return iterator(newnode);
}
iterator erase(iterator pos)
{
assert(pos != end());
node* cur = pos._node;
node* prev = cur->_prev;
node* next = cur->_next;
prev->_next = next;
next->_prev = prev;
delete cur;
return iterator(next);
}
void push_front(const T& x)
{
insert(begin(), x);
}
void pop_back()
{
erase(--end());
}
void pop_front
{
erase(begin());
}
void clear()
{
iterator it = begin();
while (it != end())
{
it = erase(it);
}
}
~list()
{
clear();
delete _head;
_head = nullptr;
}
list(const list<T>& lt)
{
_head = new node;
_head->_next = head;
_head->_prev = head;
const_iterator it = lt.begin();
while (it != lt.end())
{
push_back(*it);
++it;
}
}
private:
node* _head;
};
}