我在使用C++的鏈表時遇到問題。 我一直在尋找類這樣的:C++中的鏈接列表
class list {
private: struct node {
node * next;
int val;
};
node * head;
node * current;
public: list();
list(const list & l);
list & operator = (const list & l);~list();
void insert(int a);
void goToHead();
int getCurrentData();
void advance();
bool moreData();
};
我不會形容這裏的所有功能,我敢肯定,他們都工作正常但有運營商的聲明=:
list & list::operator = (const list & l) {
if (& l == this) return *this;
current = NULL;
node * src, * * dst;
head = (* this).head;
src = l.head;
dst = & head;
while (src) {
if (!(* dst)) { * dst = new node;
}
(* dst) - > val = src - > val;
if (src == l.current) current = * dst;
src = src - > next;
dst = & ((* dst) - > next);
}
while ((* dst) != NULL) {
node * t = (* dst) - > next;
delete * dst;
(* dst) = t;
}
return *this;
}
它複製值從一個列表到另一個列表,如果需要,添加節點或刪除它。它適用於列表相同或第二個更長(因此它必須刪除節點)。但是當它應該添加一些節點時:
==4582== Conditional jump or move depends on uninitialised value(s)
==4582== at 0x8048C52: list::operator=(list const&) (list.cpp:103)
==4582== by 0x804891B: main (testlist.cpp:38)
==4582== Uninitialised value was created by a heap allocation
==4582== at 0x402B9B4: operator new(unsigned int) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==4582== by 0x8048BDE: list::operator=(list const&) (list.cpp:93)
==4582== by 0x804891B: main (testlist.cpp:38)
我不知道這個聲明有什麼問題。感謝您的幫助。
對不起,如果格式錯了,我有一些鉻問題,這就是原因。也許有例子,但我必須使用這個例子,我有一個任務這樣做,我的意思是我有代碼示例,只需要完成它。我仍然有同樣的問題: 線93:
* dst = new node;
和103僅僅是最後的右括號
}
再次感謝您的幫助。
請正確格式化您的代碼。沒有人會讀取類似'/ dev/random'輸出的代碼。 – rightfold
我會說有很多的例子如何獲得鏈接列表的權利,沒有必要再問... –
@沒有rightfold做:) –