我在使用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做:) –