【问题标题】:Why can't modify value in object? Also How can I Improve on this Linked List?为什么不能修改对象中的值?另外我该如何改进这个链接列表?
【发布时间】:2020-07-10 21:41:14
【问题描述】:

由于我来自 java 和 python,所以我对 C++ 还很陌生。这是我对链表的尝试。我试图用数据初始化节点,但它不起作用,而是在附加函数中我必须传递数据才能显示出来。在确保最后一个节点指向 null 之前,我该如何改进这一点,我有一个内存错误,exc bad access 为什么会这样。

    #include <iostream>

using namespace std;

struct Node{
    int data;
    Node* next;
    Node(int data){
        this->data = data;
    }
};

class LinkedList{
private:
    Node* head;

public:
    void showList(){
        Node* temp = head;
        while (temp->next != NULL){
            cout << temp->data << endl;
            temp = temp->next;
            if (temp->next == NULL){
                cout << temp->data << endl;
            }
        }
    }
    void append(int data) {
        Node* nodeToAdd = new Node(data);
        nodeToAdd->data = data;
        nodeToAdd->next = NULL;

        Node* temp = head;
        if (head->next == NULL){
            head->next = nodeToAdd;

            return;
        }
        while (temp->next != NULL) {
            temp = temp->next;
        }
        temp->next = nodeToAdd;
    }

    LinkedList(){
        head->next = NULL;
        cout << "Linked list created" << endl;
    }
};

int random(int upto){
    int random = rand() % 100+1;
    return random;
}

int main() {
    LinkedList theLink;
    for (int i = 0; i < 100; ++i) {
        theLink.append(i);
    }
    theLink.showList();
    cout << "Finished" << endl;
    return 0;
}

【问题讨论】:

  • 你能更清楚地说明什么不起作用吗?
  • 代码风格保持一致,访问所有成员时使用this-&gt;,不要仅限于构造函数。
  • 没有理由改进; C++ 语言有std::list,在以后的项目中使用它。
  • 无关:当您进行后续测试时,不要忘记致电srand 为随机数生成器播种。如果您不为 RNG 播种,程序将使用默认种子运行,该种子始终相同,并始终生成相同的数字序列。在测试时始终生成相同的序列很方便,这样可以更轻松地查看您所做的更改是否确实产生了更改。
  • 也无关:rand 通常是一个非常糟糕的随机数生成器。它在产生它的限制条件下运行良好,计算机几乎没有内存,CPU 以千赫兹为单位,但现在你应该更喜欢使用tools in the &lt;random&gt; library

标签: c++ list


【解决方案1】:

尽管指针 head 从未初始化,但由于您取消引用 head(例如使用 if (head-&gt;next == NULL)...),您的程序格式错误 / 具有未定义的行为。

您的append 应该在遍历所有head-&gt;next 元素之前检查head 是否已设置为某个值。相应地调整节目列表。

class LinkedList{
private:
    Node* head = nullptr;

public:
    void append(int data) {
        Node* nodeToAdd = new Node(data);

        if (head == nullptr) {
           head = nodeToAdd;
        }
        else {
           Node* temp = head;
           while (temp->next != NULL) {
             temp = temp->next;
           }
        ...

同样,与 Node::next 类似,因此在附加第一个节点后它将失败。所以,

struct Node
{
    int data;
    Node *next;
    Node(int data)
    {
        this->data = data;
        this->next = nullptr;
    }
};

【讨论】:

  • 谢谢你,这是有道理的.这是一个更好的方法,谢谢
猜你喜欢
  • 2022-07-29
  • 1970-01-01
  • 2019-07-26
  • 1970-01-01
  • 2012-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多