使用循环向链表中添加随机数

Adding random numbers into a linked-list using loop

本文关键字:添加 随机数 链表 循环      更新时间:2023-10-16

我想将一个完全随机的数字添加到一个链表中,但是我不想将所有的代码都放在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);
}

如前所述,插入方法实际上应该是静态的,即使是自由函数,因为它只访问结构体的公共成员。

你的代码在几个方面有缺陷。

  1. instance.insert(&link_head, &random); &random没有指向Node,因此编译错误
  2. 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引用作为链接列表的,并且您将不会有一个无用的实例,总是需要从存储在列表中的实际值中进行排序。