20120918-双向链表类定义《数据结构与算法分析》

将新的节点插入双向链表的时候:

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类的删除节点的过程:

//删除双向链表中的一个节点
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的迭代器可能没有初始化  或者  这个迭代器是错误的表达,因此需要一个检测:

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类:

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));
}
posted @ 2012-09-18 20:19 xingoo 阅读(...) 评论(...) 编辑 收藏