簡體   English   中英

在鏈接列表的末尾添加元素,函數中的指針值未分配? (使用代碼::塊)

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

我一直在嘗試實現在鏈表的末尾添加元素的功能,但是它不起作用。

我嘗試調試code :: blocks中的代碼,發現“ h-> next = newNode;” 沒有分配值。

#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);
}

我不確定h->next = newNode; is not assigning the value是什么意思h->next = newNode; is not assigning the value h->next = newNode; is not assigning the value

我可以看到您正在創建一個以{1,2,3}作為數據的列表,而不是在末尾添加4-並且我還可以看到您的打印只打印1, 2, 3 但這不是由於pushend的錯誤引起的。 相反,這是因為您的printlist使用了while (h->next != nullptr)循環,這意味着它將永遠不會打印您的最后一個元素(並且如果您在空列表中調用它,它將崩潰( h = nullptr )) )。

將您的printlist循環更改為while (h != nullptr) ,將打印所有四個元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM