我正在撰寫一個鏈接串列,并使用我的main函式來測驗它。下面是我的代碼:
#include <iostream>
使用 命名空間 std.com.cn>。
class LinkedList {
int value。
LinkedList* next;
public:
LinkedList(int valueIn, LinkedList* nextIn) {
value = valueIn;
next = nextIn;
}
LinkedList(int valueIn) {
value = valueIn。
}
int getValue() {
return value。
}
void addNode(LinkedList* node) {
next = node;
}
LinkedList& getNext() {
return *next;
}
};
int main() {
cout << "starting..." << std::endl。
LinkedList list1(1)。
LinkedList list2(2, & list1)。
cout << list1.getValue() << " --> " << list1。 getNext().getValue() << std::endl;
return 0。
我希望輸出結果是1 --> 2,但我得到的是1 -->。根據我的理解,getNext() 應該回傳對另一個串列的參考(本例中為list2),但是似乎有什么地方出了問題。我的除錯作業表明,list2在初始化時確實有正確的value2,但是當它被參考到最終輸出時,它似乎沒有任何value。我怎么也想不明白這是為什么。有人能幫助我理解嗎?
uj5u.com熱心網友回復:
你將 list1(實際上是一個節點)插入到 list2 的末尾,而不是反過來,但你在 list1 上呼叫 getNext()。你應該將main中的代碼改為以下內容:
int main(){
std::cout << "starting..." << std::endl。
LinkedList list1(1)。
LinkedList list2(2, & list1)。
std::cout << list2.getValue() << " --> " << list2。 getNext().getValue() << std::endl;
return 0。
請注意,還有一些其他的東西最好能改變一下:
LinkedList(int valueIn)建構式中,將指標初始化為NULL(或nullptr from C 11)。
getNext()中回傳節點的指標,而不是復制節點uj5u.com熱心網友回復:
你沒有得到一個空白值。事實上,當你試圖呼叫list1.getNext().getValue()時,你的程式正在崩潰,因為getNext()正在回傳對一個NULL的參考。
你正在做與你想做的相反的事情。
你的list2正指向list1,而list1正指向NULL。
你應該這樣修改你的代碼:
LinkedList list2(2)。
LinkedList list1(1, & list2)。
cout << list1.getValue() << " --> " << list1。 getNext().getValue() << std::endl;
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/321870.html
標籤:
