c++ - 为什么要打印这个?
问题描述
我目前正在尝试创建一个程序来创建一个单链表,该链表接受输入,然后打印出链表中的值。下面是应该打印出值的函数。
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;
}
解决方案
h = new Node;
所以它是新对象,意思是实例化。而你做到了
pointy = h;
。所以pointy->data
会是0。
推荐阅读
- javascript - 从选项选择列表 Html-javascript 中删除一些“选项”
- node.js - 我如何将 MongoDB 聚合匹配用于数组以使用分页
- scala - 初始化演员系统wavesplatform com.protonail.leveldb.jna.LevelDBException时出错
- php - 如何在这个调试案例中用 php 7.4 交换参数?- 加入()
- python - python是否会在“if and”中的第一个错误条件下停止验证,还是在决定之前检查所有内容?
- c - 比较文件中的字符串和 C 中的 malloced 字符串
- angular - Angular 10 应用程序中的安全标头失败
- python - 如何对熊猫数据框中的每一行进行排序并获取索引?
- java - 从生成的 EditText Android Kotlin 获取输入
- javascript - 使用 FormSpy 时如何禁用 React Final Form 中的提交按钮?