实在忍不住,模仿STL写了个阉割版的List,还没加迭代器,等搞完STL源码再说吧。
```c++
pragma once
include
namespace vlyf
{
template
struct Node
{
using pointer = Node
Key key;
Node prev{nullptr};
Node* next{nullptr};
Node() = default;
Node(Key const& k) : key(k) {}
};
template <typename T> class List { private: using linkType = Node<T>::pointer; linkType head{new Node<T>}; public: List() { head->prev = head; head->next = head; } ~List(); linkType Begin() const { return head->next; } linkType End() const { return head; } linkType Search(T const&) const; linkType Erase(linkType position); void Insert(linkType position, T const& x); void PushBack(T const& x) { Insert(End(), x); } void PushFront(T const& x) { Insert(Begin(), x); } void PopFront() { Erase(Begin()); } void PopBack() { linkType tmp = End()->prev; Erase(tmp); } void Clear(); void Remove(T const& x); void Unique(); void Delete(T const& x); protected: void Transfer(linkType position, linkType first, linkType last); }; template <typename T> inline List<T>::linkType List<T>::Search(T const& k) const { if (!head) throw std::out_of_range("List is empty"); linkType p = head; while (p->key != k) { p = p->next; } return p; } template <typename T> inline void List<T>::Insert(List<T>::linkType position, T const& x) { linkType node = new Node<T>(x); node->next = position; node->prev = position->prev; position->prev->next = node; position->prev = node; } template <typename T> inline void List<T>::Delete(T const& x) { if (!x->prev) x->prev->next = x->next; else head->next = x->next; if (!x->next) x->next->prev = x->prev; delete x; } template <typename T> inline List<T>::linkType List<T>::Erase(List<T>::linkType position) { linkType nextNode = position->next; linkType prevNode = position->prev; prevNode->next = nextNode; nextNode->prev = prevNode; delete position; return nextNode; } template <typename T> inline void List<T>::Clear() { linkType cur = head->next; while (cur != head) { linkType tmp = cur; cur = cur->next; delete tmp; } head->next = head; head->prev = head; } template <typename T> inline void List<T>::Remove(T const& x) { linkType first = Begin(); linkType last = End(); while (first != last) { linkType tmp = first; tmp = tmp->next; if (x == first->key) { Erase(first); } first = tmp; } } template <typename T> inline void List<T>::Unique() { linkType first = Begin(); linkType last = End(); if (first == last) return; linkType next = first->next; while (next != last) { if (next->key == first->key) Erase(next); else first = next; next = first->next; } } template <typename T> inline void List<T>::Transfer(linkType position, linkType first, linkType last) { last->prev->next = position; first->prev->next = last; position->prev->next = first; linkType tmp = postion->prev; postion->prev = last->prev; last->prev = first->prev; first->prev = tmp; }
} // namespace vlyf
```c++
来源:https://www.cnblogs.com/vlyf/p/12040882.html