首页 > 解决方案 > 不显示任何输出

问题描述

我在用 c++ 编写链接列表实现时遇到了一个问题。每当我尝试添加一个元素时,他遵循的代码都不会显示任何输出。代码有什么问题

#include<iostream>

using namespace std;

struct Node {
    int data;
    struct Node* ptr;

    Node(int val) {
        data = val;
        ptr = NULL;
    }
};

void addItem(struct Node* head, int val) {
   struct Node* n = new Node(val);
    if(head == NULL){
        head = n;
        return;
    }
    
        struct Node* cur = head;     
        while(cur->ptr != NULL){  
            cur = cur->ptr;
        }
        cur->ptr = n;
    
}

void printList(struct Node* head) {
    struct Node* cur = head;
    while(cur != NULL) {
        cout << cur->data << " ";
        cur = cur->ptr;
    }
}

int main() {

    struct Node* head = NULL;
    
    addItem(head, 1);
    addItem(head, 2);
    addItem(head, 3);
    addItem(head, 4);
    printList(head);
    
    return 0;
}

当我运行程序时,它在终端上什么也没有显示。

输出:

[Running] cd "c:\Users\Sonu\" && g++ LinkedList.cpp -o LinkedList && "c:\Users\Sonu\"LinkedList

[Done] exited with code=0 in 3.436 seconds

标签: c++singly-linked-list

解决方案


您应该通过head双指针或引用传递。否则它将只是函数参数的一个副本,当从函数中出来时会被销毁。

void addItem(Node** head, int val) {
    Node* n = new Node(val);
    if(*head == NULL){
        *head = n;
        return;
    }
    
    Node* cur = *head;     
    while(cur->ptr != NULL){  
        cur = cur->ptr;
    }
    cur->ptr = n;        
}

// ...

addItem(&head, 1); // take the address with &

或者

void addItem(Node*& head, int val) {
    Node* n = new Node(val);
    if(head == NULL){
        head = n;
        return;
    }
    
    Node* cur = head;     
    while(cur->ptr != NULL){  
        cur = cur->ptr;
    }
    cur->ptr = n;        
}

// ...

addItem(head, 1); // no change needed

推荐阅读