C ++类 - 我的程序有什么问题?

时间:2012-06-05 03:29:48

标签: c++ class linked-list this

Insert是一种将项目附加到链接列表末尾的方法。

无法弄清楚如何编码Node为null的情况,我只想添加它。

struct Node{
       int data;
       Node *next;

       Node(int data):data(data),next(NULL){}

       void insert(int data){
            if (this==NULL){
               this=new Node(data); // compiler is complaining here.
                                    // how would I go about setting the value of this (which is presently NULL) to a new Node?
            }
       }
}

2 个答案:

答案 0 :(得分:3)

您无法为 指针指定一个值,该指针是一个特殊关键字,应始终指向有效的内存块。通过查看您的用法,您是否可以尝试这样做:

void insert(int data){
            if (!next){
               next = new Node(data);

            }

答案 1 :(得分:1)

这样的事情:

void insert(int data)
{
    Node* newNode = new Node(data);

    if (next!=NULL)
        newNode->next = next;
    next = newNode;
}

您不能直接指定'this';你需要考虑的是如何表示一个空列表,最有可能是:

Node* head = 0;

所以你按

添加第一个节点
head = new Node(data);