【问题标题】:Singly Linked List assign issue (nullptr)单链表分配问题(nullptr)
【发布时间】:2017-05-21 21:52:47
【问题描述】:

这个简单的链表有什么问题?

// linked_lst1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>

using namespace std;

class Node
{
    int data;
    Node* next;
    friend class LinkedList;
};

class LinkedList
{
private:
    Node* s;
public:
    LinkedList() : s(NULL)
    {};

    void add(int x)
    {
        Node* s1 = new Node();
        s1 = s;

        if (!s1)
        {
            s->data = x;

            return;
        }

        while (s1->next)
            s1 = s1->next;

        Node* temp = new Node;
        temp->data = x;


        s1->next = temp;
        temp->next = NULL;
    }

    void showList()
    {
        Node* s1 = new Node;
        s1 = s;

        while (s1)
        {
            cout << s1->data << " ";
            s1 = s1->next;
        }
    }
};

这里是主要部分:

int main()
{

    LinkedList list;

    list.add(3);
    list.showList();

    return 0;
}

我认为s-&gt;data = x; 中存在分配问题,但我不知道如何解决...

请注意,这只是一个教育性的简单代码,我不想使用模板等。

我想,我搞错了。

【问题讨论】:

    标签: c++ linked-list nullptr


    【解决方案1】:

    您创建一个新节点,然后立即覆盖 s1 以指向 s 指向的任何内容——您将失去对新创建节点的所有访问权限。

    【讨论】:

    • @Javadmk 了解代码的作用对您来说非常重要。现在纠正它会帮助你,但会导致你再次失败。再次查看您的这部分代码:Node* s1 = new Node(); s1 = s;。你认为这部分应该做什么?可能您现在会意识到这一点,有时您对自己的代码视而不见,因为您考虑了它应该做什么。尝试橡皮鸭方法,即向橡皮鸭(或其他东西)解释为什么需要每一行代码以及它的作用。
    • @Javadmk 另一件事,您可能想要拆分那里的代码 - 我看到一个可能的方法 Node* tail(); 搜索最后一个节点。当您有很多小方法时,更容易调试。在这种情况下,它会。
    猜你喜欢
    • 2021-06-17
    • 2011-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-25
    • 1970-01-01
    • 2021-07-28
    • 1970-01-01
    相关资源
    最近更新 更多