2012-12-17 61 views
0

我想知道這段代碼是否正確地模仿了使用鏈接列表的向量的「at」函數。這個概念是教我們鏈表,我不確定是否把pos ++放在正確的位置。有人可以幫我解決問題,並告訴我每一行都在做什麼,所以我知道它是如何從while循環退出的?截至目前,這是令人困惑的。謝謝!模仿向量的C++鏈接列表

這裏是整個項目的引擎收錄:http://pastebin.com/wyNQx3GP

謝謝你們

// This returns the countyElectionResults result at a particular point 
// in the list. 
// This is analogous to the at method in the vector class. 
countyElectionResults countyElectionList::at(int place){ 
    if(head == NULL){ 
      countyElectionResults * name = NULL; 
      return * name; 
    } 
    else{ 
      countyElectionResults * current = head; 
      int pos = 0; 
      while(pos != place && current->getNextResult() != NULL){ 
        current = current->getNextResult(); 
      } 
      pos++; 
      return * current; 
    } 
    cout << "Not Found" << endl; 
} 

回答

0

號POS ++應該是while循環中。

 
while(pos != place && current->getNextResult() != NULL) 
{ 
    current = current->getNextResult(); 
    pos++; 
}; 
+0

但它仍然有效,無論出於某種原因,我假設?你知道爲什麼嗎? – tekman22

+0

這是因爲列表結束時出現循環的其他條件。如果沒有立場pos你的pos將成爲地方? –

+0

不知道哪些情況下,它不會工作..只測試它,整個程序編譯並運行良好,即使在它使用(在)函數的情況下?有任何想法嗎?謝謝! – tekman22

0

pos ++應位於循環中,因爲您必須計算在循環時通過的位置。如果你不這樣做,那麼檢查pos != place沒有實際意義,除非地方爲零。它目前適用於迄今爲止運行的數字和案例。它不會對所有情況.....

編輯----

當我說不會工作,我的意思是,它會給錯誤的結果並不在於它不會編譯或把它給一個SIGSEV

+0

不知道哪些情況下,它不會工作..只測試它,整個程序編譯並運行良好,即使在它使用(在)函數的情況下?有任何想法嗎?謝謝! – tekman22

+0

你可以使用什麼參數和列表多久來調用(at)函數? –

1

也有在代碼中的錯誤,如果在條件爲真時return語句:

countyElectionResults countyElectionList::at(int place){ 
    if(head == NULL){ 
      // if head is null, then set name to NULL 
      countyElectionResults * name = NULL; 
      // This is segmentation fault due to dereferencing name (null) 
      return * name; 
    } 
    else{ 
      // set the current to list head and pos to 0 
      countyElectionResults * current = head; 
      int pos = 0; 
      // compare pos to place, while these are different 
      // and list does not end 
      while(pos != place && current->getNextResult() != NULL){ 
        // set current to next node 
        current = current->getNextResult(); 
      } 
      pos++; // this should be inside the loop, incremented when current 
        // advances 
      return * current; 
    } 
    cout << "Not Found" << endl; 
}