首页 > 解决方案 > 数组值意外更改

问题描述

在第一行,获取输入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。

我不明白为什么价值会改变。

标签: c++

解决方案


推荐阅读