使用循环向链表中添加随机数
Adding random numbers into a linked-list using loop
我想将一个完全随机的数字添加到一个链表中,但是我不想将所有的代码都放在main中,而是想使用面向对象的方法。我有我的标准Node类和它的头,然后在main中我想要一个循环,运行20次,然后停止添加更多。我得到了我的插入函数,以及它将如何在main中被调用,但我似乎无法得到随机数的工作。我知道你不能把一个int赋值给一个类,但我真的不知道如何将我的随机数合并到我的函数中,以便将它插入到我的列表中。
这是我的代码。观察main的第20行出现的错误。任何见解都会很棒。谢谢!Main.cpp
#include <iostream>
#include <iomanip>
#include <time.h>
#include "Node.h"
using namespace std;
int main()
{
srand(time(NULL));
Node link_head;
Node instance;
for (int i = 0; i < 20; i++)
{
int random = rand() % 100;
instance.insert(&link_head, &random);
}
}
Node.h
#include <iostream>
#include <iomanip>
#ifndef NODE_H
#define NODE_H
typedef int ElementType;
class Node
{
public:
Node();
ElementType data;
Node *next;
int insert(Node *, Node *);
};
#endif NODE_H
Node.cpp
#include <iomanip>
#include <iostream>
#include "Node.h"
using namespace std;
Node::Node()
{
this -> data = 0;
this -> next = NULL;
}
int Node::insert(Node *link_head, Node *newNode)
{
Node *current = link_head;
while (true)
{
if(current->next == NULL)
{
current->next = newNode;
break;
}
current = current->next;
}
return 0;
}
您正在向需要Node指针的函数发送int的地址。首先分配一个新节点,然后将其发送给函数。
for (int i = 0; i < 20; i++)
{
int random = rand() % 100;
Node* newNode = new Node;
newNode->data = random;
instance.insert(&linkHead, newNode);
}
如前所述,插入方法实际上应该是静态的,即使是自由函数,因为它只访问结构体的公共成员。
你的代码在几个方面有缺陷。
-
instance.insert(&link_head, &random);
&random
没有指向Node
,因此编译错误 -
int insert(Node *, Node *);
应改为static int insert(Node **, Node *);
,并按如下方式使用
Node* head = NULL;
for (int i = 0; i < 20; i++)
{
Node* newNode = new Node;
newNode->data = rand() % 100;
Node::insert(&head, newNode);
}
实现如下:
int Node::insert(Node** link_head, Node *newNode)
{
if(!link_head) {
return -1;
}
if(!(*link_head)) {
*link_head = newNode;
}
else {
newNode->next = (*link_head)->next;
(*link_head)->next = new_node;
}
return 0;
}
不同之处在于您使用head
引用作为链接列表的锚,并且您将不会有一个无用的实例,总是需要从存储在列表中的实际值中进行排序。
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 如何在C++中从两个单独的for循环中添加两个数组
- 整数不会重复超过随机数
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 如何仅为一个函数添加延迟
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 使用std::transform将一个范围的元素添加到另一个范围中
- 如何将更多文件夹添加到c++include路径
- 如何将元素添加到数组的线程安全函数?
- QT通过C++添加映射QML项目
- 如何将点击的信号和插槽添加到qt中的自定义按钮中
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 只能向C++添加一定数量的字符
- Qt和C++:将QLineEdit添加到QTabWidget中
- 如何将随机数组值一起添加到另一个数组中,然后在计算出现的值时显示它们?C++
- 如何将冒泡排序函数添加到当前随机数生成器
- 使用循环向链表中添加随机数