2012-12-22 51 views
0

列表項原因分段故障而被他們整理到鏈表

void MovieDatabase:: addActor(const string movieTitle, const string actorFirstName, const string actorLastName, const string actorRole){ 
    bool found = false; 
    Movie* temp; 
    for(Movie* m= headMovie; m != NULL; m = m-> next){ 
      if(m-> title == movieTitle){ 
       found = true; 
       temp = m; 
       break; 
      } 
    } 

    if(found){ 
      if(headCast == NULL) 
        headCast = new Cast(actorFirstName, actorLastName, actorRole, movieTitle); 
      else{ 
        Cast *c = new Cast(actorFirstName, actorLastName, actorRole, movieTitle); 
        Cast *temp = headCast; 
        for(Cast* cur = headCast; cur -> next != NULL; cur = cur -> next){ 
          if(cur ->next -> lastName < actorLastName){ 
            temp = temp -> next; 
          } 
          else{ 
            c -> next = cur -> next; 
            temp -> next= c; 
            break; 
          } 
        } 
      } 
    } 
    else 
    cout << "The movie with a " << movieTitle << " does not exist in the database,you can not add the actor. " << endl; 
    size++; 
} 

大家好我編輯的代碼,我現在不採取任何故障加入的人。但是,它沒有顯示任何輸出。這意味着它不會添加任何東西。 無論如何,我正在發送顯示代碼。

void MovieDatabase:: showActors(){ 
    for(Cast * cur= headCast; cur != NULL; cur = cur -> next){ 
     cout << cur -> lastName << endl; 
    } 
} 
+0

您的修改已不是固定我在答覆指出錯誤。現在你在循環中檢查cur-> next而不是cur,並且因爲它將以NULL開始,所以你永遠不會進入循環,也不會添加任何東西。 – JasonD

回答

1

在這段代碼:

for(Cast* cur = headCast; cur != NULL; cur = cur -> next){ 
    if(cur ->next -> lastName < actorLastName){ 

你只cur != NULL檢查,然後取消引cur->nextcur->next可能爲NULL。

tempcur都似乎指向同一節點。也許你打算讓其中一個先行一步,以便你有一個指向前一個節點的指針來插入?

下面是一個(未經測試)執行:

Cast *c = new Cast(actorFirstName, actorLastName, actorRole, movieTitle); 
    Cast *prev = NULL; // maintain a pointer to the previous node. No previous node initially. 
    Cast *cur; 
    for(cur = headCast; cur != NULL; cur = cur -> next) 
    { 
     if(cur -> lastName > actorLastName) break; // stop if we find a place to insert. 
     prev = cur;        // update previous pointer before looping. 
    } 
    if(prev != NULL) 
    { 
     prev -> next = c; // if there is a previous node, use 'c' as its next node. 
    } else { 
     headCast = c;  // otherwise 'c' is the new head node. 
    } 
    c -> next = cur;  // the 'current' node always goes after 'c'. 
+0

我只檢查cur!= NULL,因爲我想查看最後一個元素。如果我只寫cur-> next!= NULL,它不會看最後一個元素。我對嗎? –

+0

不可以。您正在檢查*過去*最後一個元素。當'cur == lastElement'時,'cur-> next'將爲NULL,並且'cur-> next-> lastName'爲segfaulting。您需要稍微重構您的循環,以便您只查看有效節點,並維護指向前一個節點的指針以便插入。 – JasonD

+0

但我通過說 - >下一個 - > lastName來控制另一個元素的指針。其實這也是我的目標.. –