2014-03-31 49 views
0

我今天早些時候在這裏發佈了一個問題,但它非常大,所以現在提供了更多的細節。在鏈表中返回最大值

我想從鏈表返回最大值,但它只返回我輸入的第一個值?

結構:

struct Stock{ 

string itemName; 
int itemStock; //100 crisps etc... 
double individualItemCost; 
double totalSockValue; 
Stock* next; 

};

如何調用該函數:

Stock * g = Largest(head, sizeOf); 
cout << "Name: " << g->itemName << " Stock: " << g->itemStock << endl; 

實際的功能:

Stock* Largest(Stock*& list, int size) 

{

Stock *current; 
current = (list+0);// start_ptr; 
int largestValue = 0; 
if (current!=NULL) 
{ 
    while (current->next!=NULL) 
    { 
     if (current->itemStock < largestValue) 
     { 
      largestValue = current->itemStock; 
      current = current->next; 
     } 
     else 
     { 
      current = current->next; 
     } 
    } 
} 
return current; 

}

它返回的第一個值我輸入作爲反對 最大的價值,任何建議都會有幫助。

這是我正在讀入只是讓你知道鏈表:

while (i < sizeOf) 
{ 
    cout << "Please enter the students name: " << endl; 
    cin >> head->itemName; 
    cout << "Please enter the item stock: " << endl; 
    cin >> head->itemStock; 
    cout << "Please enter the item price: " << endl; 
    cin >> head->individualItemCost;  

    push(head,head->itemName, head->itemStock, head->individualItemCost); //Push back everything in head 
    i++; 

} 

謝謝!

回答

1

你的問題就在這裏:

if (current->itemStock < largestValue) 
    { 
     largestValue = current->itemStock; 
     current = current->next; 
    } 
    else 
    { 
     current = current->next; 
    } 

不管你的代碼需要哪個分支,current總是被設置到列表中的下一個元素。既然你返回current,你將返回列表的最後一個元素,而不管最大值是多少。

我不打算爲您提供解決方案,但我會給您一個提示:您需要一個類型爲Stock*的附加變量,它非常類似於變量largestValue

+0

右鍵確定歡呼,所以你的意思是像設置一個類型的股票變量current-> itemstock,然後返回? – user2799788

+0

差不多。只有'current'沒有' - > itemstock'。 – datenwolf

+0

啊!我想我沒有工作!謝謝你的幫助,一直困在這個很長一段時間哈哈。只是最後一個問題,我現在有內存泄漏,因爲我正在啓動這個股票* temp; \t temp = new Stock;是否有沒有使用動態變量呢? – user2799788

0

您試圖返回最大的值,但您測試值是否更小。您當前的代碼如下所示:

if (current->itemStock < largestValue) 
{ 
    largestValue = current->itemStock; 
    // (...) 
} 

在邏輯上等於「從兩個值,選擇較小並將其設置爲最大的」。

最重要的是,如果您只需要數字,即使返回largestValue而不是current,您也可以遍歷整個列表,而無需記住哪個股票最大。

+0

是的當然哈哈,我一直在編輯以前的代碼,顯然錯過了那件簡單的事情;感謝您的實現! – user2799788