From aa532447c9be247ca122b325a680b7d6b1061b0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=82=B9=E6=99=93=E8=88=AA?= <1210603696@qq.com> Date: Wed, 26 Nov 2014 10:13:20 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E6=88=90List=E7=9A=84=E5=A4=B4?= =?UTF-8?q?=E5=88=A0=E9=99=A4=E5=92=8C=E5=B0=BE=E5=88=A0=E9=99=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TinySTL/List.h | 40 +++++++++++++++++++++++++++++++++++++--- 1 file changed, 37 insertions(+), 3 deletions(-) diff --git a/TinySTL/List.h b/TinySTL/List.h index 30cd4f6..4e84608 100644 --- a/TinySTL/List.h +++ b/TinySTL/List.h @@ -12,12 +12,13 @@ namespace TinySTL{ template struct node{ T data; + node *prev; node *next; List *container; - node(const T& d, node *n, List *c): - data(d), node(n), container(c){} + node(const T& d, node *p, node *n, List *c): + data(d), prev(p), node(n), container(c){} bool operator ==(const node& n){ - return data == n.data && next == n.next && container == n.container; + return data == n.data && prev == n.prev && next == n.next && container == n.container; } }; //the class of list iterator @@ -40,6 +41,15 @@ namespace TinySTL{ ++*this; return res; } + listIterator& operator --(){ + p = p->prev; + return *this; + } + listIterator operator --(int){ + auto res = *this; + --*this; + return res; + } T& operator *(){ return p->data; } T* operator &(){ return &(operator*()); } bool operator ==(const listIterator& it){ @@ -82,7 +92,9 @@ namespace TinySTL{ } void push_front(const value_type& val); + void pop_front(); void push_back(const value_type& val); + void pop_back(); iterator begin()const{ return head; } iterator end()const{ return tail; } @@ -91,23 +103,45 @@ namespace TinySTL{ nodePtr res = nodeAllocator::allocate(); res->container = this; res->data = val; + res->prev = nullptr; res->next = nullptr; return res; } + void deleteNode(nodePtr p){ + p->prev = nullptr; + p->next = nullptr; + nodeAllocator::deallocate(p); + } }; template void List::push_front(const value_type& val){ auto node = newNode(val); + head.p->prev = node; node->next = head.p; head.p = node; } template + void List::pop_front(){ + auto oldNode = head.p; + head.p = oldNode->next; + head.p->prev = nullptr; + deleteNode(oldNode); + } + template void List::push_back(const value_type& val){ auto node = newNode(); (tail.p)->data = val; (tail.p)->next = node; + node->prev = tail.p; tail.p = node; } + template + void List::pop_back(){ + auto newTail = tail.p->prev; + newTail->next = nullptr; + deleteNode(tail.p); + tail.p = newTail; + } } #endif \ No newline at end of file