c++ - 在列表中插入值
问题描述
我想不通....我的代码没有打印任何东西。我需要创建一个不同的节点还是我编写了错误的代码?请帮忙。一个解释将不胜感激。代码只能去它说“从这里开始//从这里结束。不能修改之外的任何内容。
#include <iostream>
using namespace std;
class node
{
int value;
node* next;
public:
node(int value, node* next)
{
this->value = value;
this->next = next;
}
void print()
{
node* current = this;
while (current != nullptr) {
cout << current->value << " ";
current = current->next;
}
}
//Add the value end at the end of the list (i.e. after the last element)
void add(int n)
{
**// Your code starts here**
node* curr = this;
curr->value = n;
if (curr->next == NULL)
{
curr->add(n);
}
curr->next = NULL;
**// Your code ends here**
}
//Return the sum of all the elements in the list
int sum()
{
**// Your code starts here**
int sum = 0;
node* curr = this;
while (curr != NULL)
{
sum += curr->value;
curr = curr->next;
}
return sum;
**// Your code ends here**
}
//Multiplies each element in the list by n
void mult(int n)
{
**// Your code starts here**
node* curr = this;
while (curr != NULL)
{
curr->value = curr->value * n;
curr = curr->next;
}
**// Your code ends here**
}
//Find the maximum value in the list
int max()
{
**// Your code starts here**
node* curr = NULL;
int max_value = curr->value;
while (curr != NULL)
{
if (curr->value > max_value)
max_value = curr->value;
curr = curr->next;
}
return max_value;
**// Your code ends here**
}
};
//After
int main()
{
node* n = NULL;
cout << "//Inserting values at the end" << endl;
n->add(10);
n->add(20);
n->add(30);
cout << endl << "10 20 30" << endl;
cout << "//printing the values" << endl;
n->print();
cout << endl << "//finding sum for the values in the list" << endl;
cout << n->sum();
cout << endl << "//calling multiply funciton with 4 as n" << endl;
n->mult(4);
n->print();
cout << endl << "//finding the max value in the list" << endl;
cout << n->max();
}
预期值: 原始:1 2 3 4 5 6 7 8 9 10 11 总和:66 乘以 4:4 8 12 16 20 24 28 32 36 40 44 最大值:44
解决方案
推荐阅读
- ios - 没有从 iOS 中的位置管理器获取我的当前地址
- php - 使用 mysqli 类在 PHP 中返回 MySQL 查询
- javascript - Intersection Observer API:观察视口的中心
- unix - Unix 显示学生记录
- python - 如何在 Python 中迭代字符串的长度时迭代字符串
- django-mptt - 使用 TreeManager 时 get_children() 方法出现问题。错误的结果
- c++ - 将具有面的对象旋转到另一个对象时出现问题。[C++]
- swift - 斯威夫特:字符串开始(带:) vs hasPrefix
- hive - 当 ACID 属性关闭时,如何更新外部 Hive 表中的行?
- java - 错误:java:无效标志:--add-exports=javafx.graphics/com.sun.javafx.application=ALL-UNNAMED