将节点添加到链接列表的前面,然后计算链接列表中的节点数

时间:2019-08-09 00:50:17

标签: c++ class linked-list

我想通过调用一个对象在列表的前面添加一个节点并打印列表的长度。到目前为止,我一直遇到细分错误。我想要足够基本的东西,可以从中构建想法:

#include <iostream>

using namespace std;

class Node {
  public:
    int data;
    Node *next; //creating a pointer to store the address of the next node or null (at the end of a linked list)
   int key;

    Node(int d){
        data = d;
        next = NULL;
        key = -1;
    }
};

class LinkedList {
public:
    Node *head;
    LinkedList (){
        head = NULL;

    }

    void addNodetoFront(int data){
        Node *n = new Node(data);//allocate memory on the heap with address that is returned to n (pointer)


        n->next=head;
        head=n;


        if(n != NULL){
            n->key = n->next->key+1;
        }
        else{
            n->key = 1;
        }
    }

};

int main(){
    LinkedList linkedlist;

    linkedlist.addNodetoFront(2);
    linkedlist.addNodetoFront(3);
    linkedlist.addNodetoFront(4);
    linkedlist.addNodetoFront(5);
    linkedlist.addNodetoFront(26);
    linkedlist.addNodetoFront(27);
    linkedlist.addNodetoFront(9);
    linkedlist.addNodetoFront(45);
    linkedlist.addNodetoFront(87);

    return 0;
}

期望是9个节点的链接列表,程序将打印9个元素。

1 个答案:

答案 0 :(得分:2)

您的head以NULL开头。当您添加第一个节点时,该节点将成为头,并且其next指针将变为NULL。现在,看看这个:

if(n != NULL){
    n->key = n->next->key+1;  // But n->next is NULL :(
}

以上,n->next->key是未定义的行为,因为您要取消引用NULL指针。此外,虽然实际上n不可能为NULL,但是假设n 假设可能为NULL的以下逻辑是疯狂的:

else{
    n->key = 1;  // But you said n was NULL :(
}

这一切有意义的唯一方法是,如果您的考试中确实有错字,并且您的意思是:

if(n->next != NULL)

将所有内容放在一起,使您的函数如下所示:

void addNodetoFront(int data)
{
    Node *n = new Node(data);

    n->next = head;
    head = n;

    if (n->next != NULL) {
        n->key = n->next->key + 1;
    } else {
        n->key = 1;
    }
}

或者,以下更紧凑的样式实现了相同的效果:

void addNodetoFront(int data)
{
    Node *n = new Node(data);
    n->next = head;
    n->key = (head ? head->key + 1 : 1);
    head = n;
}