在Linked List c ++中的某个位置插入一个节点

时间:2015-10-07 02:21:51

标签: c++ insert doubly-linked-list

我有一个链表,我需要在" iterator"的位置插入一个节点。是。

下面是插入函数(我已经模板化):

    template <class T>
    void List<T>::insert(T x)
   {
        if (size=0)
       {
           cout << "adding postion to head because empty list" << endl;
          NodeRef newNode = new Node(x);
         tail = head = newNode;
      }
     else
     {
        NodeRef temp = new Node(x);
        temp->previous = iterator;
       iterator->next = iterator;
     }
   }

下面是链表类(我也模板化了):

        class List
         {

         private:
        struct Node
        {
         T data;
         Node* next;
         Node* previous;

            Node() : next(NULL), previous(NULL) {} //define our own default constuctor
         Node(T data) : next(NULL), previous(NULL), data(data) {}
         };

     typedef struct Node* NodeRef;

    NodeRef head;
     NodeRef tail;
     NodeRef iterator; //points to one node at a time
     NodeRef current1;//temp 
    int size;
   public:
    void insert(T);Inserts a new element into the list in the position after the "iterator"
    void scroll() {iterator = iterator->next;}

当我调用插入函数时,我遇到了问题。滚动功能正常。

1 个答案:

答案 0 :(得分:0)

iterator->next = iterator不正确并创建循环。由于上一行是temp->previous = iteratoriterator->next应该指向temp。一旦更新了两个链接,您就应该为列表中的任何有效节点n->next->prev == n