简体   繁体   English

在链接列表的末尾添加元素,函数中的指针值未分配? (使用代码::块)

[英]Adding element at end of a linked list, in function the pointer value not getting assigned? (using code::blocks)

I have been trying to implement function to add element at the end of an linked list but it is not working. 我一直在尝试实现在链表的末尾添加元素的功能,但是它不起作用。

I tried to debug code in code::blocks and found that "h->next = newNode;" 我尝试调试code :: blocks中的代码,发现“ h-> next = newNode;” is not assigning the value. 没有分配值。

#include <iostream>
using namespace std;

class Node{
public:
    int data;
    Node* next;
};

void printlist(Node* h){
    while(h->next!=nullptr){//or h!=0
        cout<<h->data<<endl;
        h = h->next;
    }
}

void pushend(Node* h, int newData){
    Node* newNode;
    newNode = new Node;
    newNode->data = newData;
    newNode->next = nullptr;
    while(h!=nullptr){
        if(h->next == nullptr){
            h->next = newNode;
            break;
        }
        h = h->next;
    }
}

int main(){
    Node* head;
    Node* second;
    Node* third;   
    head = new Node;
    second = new Node;
    third = new Node;  
    head->data = 1;
    head->next = second;  
    second->data = 2;
    second->next = third; 
    third->data = 3;
    third->next = nullptr;
    int newData = 4;
    pushend(head,newData);
    printlist(head);
}

I am not sure what you mean by h->next = newNode; is not assigning the value 我不确定h->next = newNode; is not assigning the value是什么意思h->next = newNode; is not assigning the value h->next = newNode; is not assigning the value . h->next = newNode; is not assigning the value

I can see that you are making a list with {1, 2, 3} as data, and than adding a 4 to the end - and I can also see that your print only prints 1, 2, 3 . 我可以看到您正在创建一个以{1,2,3}作为数据的列表,而不是在末尾添加4-并且我还可以看到您的打印只打印1, 2, 3 But that is not caused by an error in pushend . 但这不是由于pushend的错误引起的。 Instead it is because your printlist uses a while (h->next != nullptr) loop, which means that it will never print your last element (and that it will crash if you ever call it on an empty list ( h = nullptr )). 相反,这是因为您的printlist使用了while (h->next != nullptr)循环,这意味着它将永远不会打印您的最后一个元素(并且如果您在空列表中调用它,它将崩溃( h = nullptr )) )。

Change your printlist loop to while (h != nullptr) and all four elements will be printed. 将您的printlist循环更改为while (h != nullptr) ,将打印所有四个元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM