將新的節點插入雙向鏈表的時候:this
iterator insert(iterator itr,const Object & x)//向雙向鏈表中插入一個x節點 { Node *p = itr.current; theSize++; return iterator(p->prev = p->prev->next = new Node(x,p->prev,p)); }
LIST類的刪除節點的過程:spa
//刪除雙向鏈表中的一個節點 iterator erase(iterator itr) { Node *p = itr.current; iterator retVal(p->next); p->prev->next=p->next; p->next->prev=p->prev; delete p; theSize--; return retVal; } iterator erase(iterator start,iterator end) { for(iterator itr = from;itr != to; ) itr = erase(itr); return to; }
傳遞給erase insert的迭代器可能沒有初始化 或者 這個迭代器是錯誤的表達,所以須要一個檢測:code
protected: const List<Object> *theList; Node *current; const_iterator(const List<Object> & lst,Node *p): theList(&lst),current(p)' { } void assertIsValid() const { if(theList == NULL || current == NULL || current == theList->head) throw IteratorOutOfBoundsException(); }
帶有附加錯誤檢測的insert類:blog
iterator insert(iterator itr.const Object & x) { itr.assertIsValid(); if(itr.theList !=this) throw IteratorMismatchException(); Node *p = itr.current; theSize++; return iterator(*this,p->prev=p->prev->next=new Node (x,p->prev,p)); }