c++ - 数组值意外更改
问题描述
在第一行,获取输入n
(节点数)、m
(边数)、start
(起始节点数)并获取无向m
边/最后,我想打印出 dfs 结果。但是,当我使用 时Node*
,它会发生变化。我不打算改变。
class Node {
private:
int n;
Node* next = 0;
public:
Node(int _n) {
n = _n;
}
Node() {};
Node* getNext() {
return next;
}
void setNext(Node* ptr) {
next = ptr;
}
};
下面的代码是主要问题。
Node* arr = new Node[n + 1];// use 1 to n
for (int i = 1; i <= m; i++) {
int num1 = 0, num2 = 0;
cin >> num1 >> num2;
if (!arr[num1].getNext())
arr[num1].setNext(&Node(num2));
else {
Node* tptr = arr[num1].getNext();
while (tptr->getNext()) tptr = tptr->getNext();
tptr->setNext(&Node(num2));
}
}
我试图将相邻节点(到节点'i')保存在 arr[i] 中。
示例代码是:
4 5 1
1 2
1 3
1 4
我预期的结果结构是 arr[1] -> 2 -> 3 -> 4,但真正的结果是 arr[1]-> 2 -> 4 -> 4。
我不明白为什么价值会改变。
解决方案
推荐阅读
- java - maven - 多模块项目访问父源代码并避免冗余依赖声明
- flutter - 在 chrome 上测试时,我可以使 SharedPreferences 正常工作(调试版本或发布版本)吗?
- python - 从 setup.cfg 创建虚拟环境
- python - 请帮助我进行 Django 模型对象验证
- reactjs - 如何阻止选择组件重新对齐
- c++ - 在集合中存储相等的对象
- python - 尝试执行 for 循环以使网格中的元素彼此分开
- neo4j - 正确使用 UNWIND 和 COLLECT
- python - Django:在 Admin ListView 中更改列标题而不会失去可排序性
- html - CSS 逻辑属性和 Box-Shadow