2013-10-22 46 views
0

我想按字母順序將某些人的名字插入到一個循環的雙向鏈表中,但我只能添加到三個,而我不是確定爲什麼發生這種情況。我將新節點傳遞給insert函數,創建一個指向它的指針,並遍歷整個列表以找到正確的插入點。但是,如果名稱超過三個,則會刪除一個節點並插入另一個節點。有人能幫我解決這個問題嗎?尋找在一個圓形雙向鏈表中插入的正確位置

其他信息:

  • 每個Node有兩個指針稱爲nextprevstring稱爲data作爲數據成員
  • List類包含插入件和顯示功能,和一個頭指針,其指向一個虛擬頭節點。這頭節點的nextprev指針指向自身時List初始化

這是插入功能,我已經寫了:

void List::insert(Node newObject) 
{ 


    Node *toInsert = &newObject; 
    Node *cur = head->next; 

    while((cur != head) && (newObject.data > cur->data)) 
    { 
      cout << "Is this loop entered?" << endl; 
      cur = cur->next; 

    } 

    toInsert->next = cur; 
    toInsert->prev = cur->prev; 

    cur->prev = toInsert; 
    toInsert->prev->next = toInsert;   

} 

而且我main.cpp

#include "list.h" 
#include "node.h" 

using namespace std; 

int main() 
{ 


    Node nikhil = Node("Nikhil"); 
    Node kaustubh = Node("Kaustubh"); 
    Node jon = Node("Jonathan"); 
    Node james = Node("James"); 
    Node elias = Node("Elias"); 
    Node kenny = Node("Kenny"); 

    List suiteMates; 

    suiteMates.insert(nikhil); 
    suiteMates.insert(kaustubh); 
    suiteMates.insert(jon); 
    suiteMates.insert(james); 
    suiteMates.insert(elias); 
    suiteMates.insert(kenny); 

    suiteMates.display(); 
} 

回答

0

你的insert函數插入一個局部變量,當控制超出函數時,該局部變量超出範圍。稍後,您嘗試取消引用指向該消失對象的指針,這是未定義的行爲

+0

感謝您的幫助! – rafafan2010