提问者:小点点

在指定的自定义类迭代器位置插入节点


我试图在指定的位置插入一个节点,问题是插入发生在我想要的位置之后的一个位置。 例如:

List.insert(List.Begin()++,100)中的1,2,3,4,5,6,7处插入100,结果是:

1,2,100,3,4,5,6,7

我想减少迭代器,然后插入,但这将是一个解决办法,在我的代码中一些有缺陷的逻辑,但我看不到它在哪里。

插入函数

iterator insert(iterator position, const T& value) {

        Node* newNode = new Node(value);

        if (position == List<T>::iterator(head_)) {
            newNode->next_ = head_;
            head_ = newNode;
        }
        else if (!position.iNode->next_) {
            position.iNode->next_ = newNode;
        }
        else {

            Node* tmp = new Node(value);
            tmp->next_= position.iNode->next_;
            position.iNode->next_ = tmp;
        }

        return position;
    }

迭代器类

class iterator
    {
    public:

        Node* iNode;
        iterator(Node* head): iNode(head){ }
        ~iterator() {}


        T& operator*() {
            return  iNode -> value_;
        }
    
        iterator& operator++() {
            iNode = iNode->next_;
            return *this;
        }

        iterator operator++(int ignored) {
            iNode = iNode->next_;
            return *this;
        }

        //! Is this iterator pointing at the same place as another one?
        bool operator== (const iterator& it) const {
            return this->iNode == it.iNode;
        }

        //! Is this iterator pointing at a different place from another?
        bool operator!= (const iterator& it) const {
            return this->iNode != it.iNode;
        }
    };

节点类

class Node {
    public:
        Node(T value) : value_(value) {}

        T value_;
        Node* next_;
        Node* prev_;

        Node* head_;
        Node* tail_;
    };


共1个答案

匿名用户

此处插入的问题是:

iterator insert(iterator position, const T& value) {

        Node* newNode = new Node(value);

        if (position == List<T>::iterator(head_)) {
            newNode->next_ = head_;
            head_ = newNode;
        }
        else if (!position.iNode->next_) {
            position.iNode->next_ = newNode;
        }
        else {

            Node* tmp = new Node(value);
            tmp->next_= position.iNode; //fixed
            position.iNode->next_ = tmp;
        }

        return position;
    }

在迭代器位置之后插入一个新节点。 但您需要将其插入到新节点之前。

顺便说一下,我在自己的List类中测试了它。 如果出了什么问题,就给我的帖子加个评论吧。