【问题标题】:Not showing any output不显示任何输出
【发布时间】:2021-10-01 07:22:36
【问题描述】:

我在用 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++ 中的参数默认是按值传递的,这意味着调用中使用的值复制到参数变量中。这意味着当您修改参数变量时(例如在 addItem 函数中对 head 的赋值),您只会修改局部变量,而不是调用中使用的原始变量。
  • 那么,我现在能做什么?你能给我解决办法吗?
  • 一个函数可以修改一个东西,如果你将一个指针传递给它指向那个东西。即使事物本身是指针也是如此。指针没有什么特别之处。
  • 改为通过reference
  • struct Node* n = new Node(val); -- 这里不需要指定struct,在代码的其他地方也不需要指定。只需Node* n = new Node(val); 就足够了。 C++ 不是 C。

标签: c++ singly-linked-list


【解决方案1】:

您应该通过双指针或引用传递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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-26
    • 2016-07-28
    • 2019-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多