2013-11-01 67 views
1

我有問題在一個間隔位置之後插入一個節點,保持未處理的異常,即使我檢查指向的所有鏈接,它們都是全對了。有人會看看我的代碼,看看有什麼問題嗎?在deque類中的一個位置後插入一個節點

void insert_after(DequeIterator<E>& iter, E x) 
{ 
    if(_size == 0) 
    { 
     insert_front(x); 
    } 
    else 
    { 
     assert(!iter.at_end()); 

     // need to check, if its the iter is the last element 
     // do insert_back instead 
     if(iter.node() == _tail) 
      insert_back(x); 
     else 
     { 
      // create a temp2 pointer to hold the address of iter 
      DNode<E>* temp2 = iter.node(); 
      // set temp2 equal to the address of the node after 
      // iter before inserting 
      iter.node()->next()->set_next(temp2); 
      // create a new node to insert 
      DNode<E>* temp = new DNode<E>(iter.node(), x, temp2); 
      // set the iter->next to hold the address of the new node 
      iter.node()->next()->set_next(temp); 
      //set the address of temp2->prev to hold the address 
      // of the new node. 
      // This is also where I got the exception error !!!! 
      temp2->prev()->set_prev(temp); 
      _size++; 
     } 
    } 
} 
+1

這是你自己的deque實現嗎?如果那麼這將有助於查看該代碼,否則這段代碼並沒有太多說明。 – edorado

回答

1

只是我的一般想法。你實際上沒有在節點上做任何迭代,那麼爲什麼你需要一個迭代器呢?引用或指針也可以。我會初始化我的節點,如

DNode<E>* temp = new DNode<E>(iter.node(), x, iter.node()->next()); 
// Initialize new node inbetween previous nodes 
temp->prev()->set_next(temp); temp->next()->set_prev(temp); 
// Cut ties between nodes to avoid cycles. 

假設左邊是prev,右邊是next。然後你所要做的就是設置iter。同樣,你的變數也會讓你記住它們是什麼。它看起來像這個代碼中你正在使用當前節點,然後在它跟在你之後對節點說。然後在它之前和之後用當前節點初始化新節點。然後,您將新節點轉到它應該是當前節點之前的節點,並將當前節點設置爲前一個節點。這是假設這些函數完成了我的想法認爲他們會爲雙向鏈表執行的操作,這顯然是您正在進行的操作。

1

建議的解決方案

你有序列a, c,與itera指指點點,你想a, b, c與價值x存儲在新節點b,對不對?每個節點都有一個prev和一個next指針,可以使用這些名稱的方法讀取指針,並使用setter方法進行設置,對吧?那就試試這個:

DNode<E>* a = iter.node(), c = a->next(); // both ends of the insert location 
DNode<E>* b = new DNode<E>(a, x, c);  // assuming constructor sets pointers 
a.set_next(b); 
c.set_prev(b); 

問題分析

現在爲什麼你的代碼會失敗?

iter.node()->next()->set_next(temp2); 

你爲什麼要修改next指針c?這應該保持不變!

iter.node()->next()->set_next(temp); 

同樣的問題。此外,這似乎覆蓋了以前的呼叫,所以這似乎毫無意義。

temp2->prev()->set_prev(temp); 

現在正在修改aprev指針的節點?更糟。

+0

非常感謝您的幫助。 –

相關問題