使用For循环创建链表(c++)

Creating Linked List using For Loop (c++)

本文关键字:c++ 链表 创建 For 循环 使用      更新时间:2023-10-16

我试图使用for循环创建一个链表,但create()方法中的for循环中的'new'并没有完全分配一个新插槽来存储新数据。结果,当我试图打印列表时,我得到了一个无限循环。谁能告诉我这是怎么回事?

struct node
{
    double value;
    node * next_ptr;
    node(){}
    node(double val, node * p): value(val), next_ptr(p) {}
    ~node(){}
};
node * create()
{
    using namespace std;
    node temp = {0, nullptr};
    node * result;
    for(int i=1; i<5; ++i)
    {
        result = new node;
        result->value = i;
        result->next_ptr = &temp;
        temp = *result;
    }
    return result;
};

你可能会得到一个无限循环的原因是:

temp = *result;

您正在将*result的值复制到类型为node的新对象中,该对象与您创建的对象无关。

你要做的是存储一个指针,而不是:

node* temp = nullptr;
node* result;
for(int i=0; i<5; ++i)
{
    result = new node;
    result->value = i;
    result->next_ptr = temp;
    temp = result;
}
return result;

现场演示


学习值的一部分,只坚持std::forward_liststd::list,而不是列表。或者最好使用std::vector或其他容器(取决于您对容器的使用)。

创建一个简单的链接在for循环

#include <iostream>
class LinkedList {
  public:
  int value;
  LinkedList * next;
};
int main()
{
  LinkedList *List = nullptr;
  LinkedList *head = List;
  LinkedList *prev;
  for (int i=0; i< 3;i++)
  {
    LinkedList *temp = new(LinkedList);
    temp->value = i;
    temp->next = nullptr;
    if (head == nullptr)
    {
      head = temp;
      prev = head;
    }
    else
    {
      prev->next = temp;
      prev = temp;
    }
  }
}