首页 > 解决方案 > 为什么要打印这个?

问题描述

我目前正在尝试创建一个程序来创建一个单链表,该链表接受输入,然后打印出链表中的值。下面是应该打印出值的函数。

void Linked_list_return()
{
    Node* pointy;
    pointy = h;
    cout << pointy -> data;
} 

但不是返回值,而是打印出 0 。我不知道下面有什么问题是完整的程序。

#include <iostream>
using namespace std;

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

void Linked_list(int input_data, int &decision);
void Linked_list_return();
Node* h;

int main()
{
    int size_of;
    int input;
    cout << "How many numbers would you like to enter? " << '\n';
    cin >> size_of;
    cout << "What are the numbers?" << endl;
    while (size_of > 0)
    {
        cin >> input;
        Linked_list (input, size_of);
        size_of--;
    }
    cout <<  "Completed!" << endl;
    Linked_list_return();
    return 0;
}

void Linked_list(int input_data, int &decision)
{
    Node* n;
    Node* t;

    n = new Node();
    t = new Node();
    h = new Node();
    t->data = input_data;
    t->next = n;
    t = n;

    if (decision == 0)
    {
        n = new Node();
        t-> data = input_data;
        t -> next = NULL;
    }
}

void Linked_list_return()
{
    Node* pointy;
    pointy = h;
    cout << pointy -> data;
}

标签: c++

解决方案


h = new Node; 所以它是新对象,意思是实例化。而你做到了 pointy = h;。所以pointy->data会是0。


推荐阅读