我有在線性串列中搜索鍵的功能,但是當我想在元素上回傳指標時出現錯誤。
struct Item
{
datatype key;
Item* next;
Item* prev;
};
int List::search(int x)
{
Item* temp = head;
if (head == NULL)
{
cout << "Empty List" << endl;
}
while (temp != NULL)
{
if (temp->key == x)
{
break;
}
else
{
temp = temp->next;
}
}
return *temp;\\here i have a error
}
uj5u.com熱心網友回復:
如何回傳指向線性串列中專案的指標
很明顯,對于初學者來說,您需要將函式的回傳型別從int更改為Item *。
Item * List::search( int x );
在函式中,您確實需要回傳一個指標而不是指向的專案。
該函式不應輸出任何訊息。函式的用戶將根據是否回傳空指標來決定是否輸出任何訊息。
該函式應該為常量和非常量串列多載。
這里顯示了如何定義它
Item * List::search( int x )
{
Item *target = head;
while ( target != nullptr && target->key != x )
{
target = target->next;
}
return target;
}
和
const Item * List::search( int x ) const
{
const Item *target = head;
while ( target != nullptr && target->key != x )
{
target = target->next;
}
return target;
}
uj5u.com熱心網友回復:
這里:
int List::search(int x)
{
Item* temp = head;
...
return *temp;\\here i have a error
}
如果你想獲得一個元素的指標,那么函式應該回傳Item*,而不是int。
如果temp是Item*,則*temp是Item。它既不是 anItem*也不是int。
uj5u.com熱心網友回復:
也許嘗試改變:
Item* List::search(int x)
{
Item* temp = head;
if (temp == NULL)
{
cout << "Empty List" << endl;
return NULL;
}
while (temp != NULL)
{
if (temp->key == x)
{
return temp;
}
else
{
temp = temp->next;
}
}
return NULL;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/351416.html
