2015-10-07 81 views
0

我有一個鏈表,我需要在「迭代器」位置插入一個節點。在鏈表中的某個地方插入一個節點C++

下面

是插入功能(這是我模板):

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;} 

當我打電話插入功能,我遇到了問題。滾動功能正常工作。

回答

0

iterator->next = iterator不正確,並創建一個循環。由於上一行是temp->previous = iterator,iterator->next應該指向溫度。一旦你更新了這兩個鏈接,你應該有n->next->prev == n列表中的任何有效節點。