【发布时间】:2018-02-17 21:34:35
【问题描述】:
我开始学习 C++ - 特别是指针。我想我会尝试一个基本的链表。这是我的代码:
#include <iostream>
using namespace std;
struct Linked {
Linked *next;
string val;
};
Linked newLinked(string val);
Linked addLinked(Linked l, string val);
void printLinked(Linked l);
Linked newLinked(string val) {
Linked l;
l.val = val;
l.next = NULL;
return l;
}
Linked addLinked(Linked l, string val) {
Linked n = newLinked(val);
n.next = &l;
return n;
}
void printLinked(Linked l) {
Linked *r = &l;
while (r != NULL) {
cout << (*r).val << endl;
r = (*r).next;
}
}
int main() {
Linked list = newLinked("This is the root node.");
list = addLinked(list, "This is the second node.");
list = addLinked(list, "This is the third node.");
list = addLinked(list, "This is the fourth, and final, node.");
printLinked(list);
return 0;
}
对不起,如果我的格式很糟糕或者我违反了惯例,我还在学习这些。 (如果你愿意,请继续指出我可以如何改进我的代码风格,我来自 Java/JS 背景!)
运行时,我得到这个:
This is the fourth, and final, node.
�;��R�;��R
This is the fourth, and
�;��R�;��R
我的猜测是,包含较早字符串的内存正在被覆盖——“这是第四个,并且”的长度与“这是第二个节点”的长度相同。
不幸的是,我不知道为什么会这样......我希望这里的某人能够指出我(哈哈)正确的方向。
【问题讨论】:
-
在
addLinked你写n.next = &l;。l是一个参数,只存在到函数结束然后消失。n.next然后将指向垃圾。正确的方向应该是here。 -
不使用值工厂函数
newLinked,只需定义类Linked的构造函数即可。 -
-> 表示法等同于“(*).”,所以你可以(并且应该)用 r->val 代替 (*r).val
-
你的所有函数都应该收到并返回
Linked* -
互联网上有大量的链表示例和教程,您可以与您的版本进行比较。