c++ - 链表问题

标签 c++ linked-list

我写的链表有问题。我不知道是我的插入函数有问题,还是我的遍历函数不正确。我希望有一些意见。旁注,我现在正在 main 中初始化列表,因为我不知道我的 initNode 函数是否正确。

#include <iostream>

using namespace std;

typedef struct Node
{
   int data;
   Node *next;
};

void initNode(Node *head)
{
   head = new Node;
   head->next = NULL;
}

void insertNode(Node *head, int x)
{
   Node *temp;
   temp = new Node;
   temp->data = x;

   temp->next = head;
   head = temp;

}

void traverse(Node *head)
{
   Node *temp;
   temp = head;

   if(head == NULL)
   {
      cout << "End of list. " << endl;
   }
   else
   {
      while(temp != NULL)
      {
         cout << temp->data << " ";
         temp = temp->next;
      }
   }

}

int main()
{
   Node *head;
   head = NULL;

   insertNode(head, 5);
   insertNode(head, 5);

   traverse(head);

   return 0;
}

最佳答案

您的 head 没有从 insertNode 返回到 main。请注意,即使 head 是一个指针,指针本身也是一个值,对指针值的任何更改都不会反射(reflect)在 main 中。最简单的解决方案是传回 head 的更新值:

Node *insertNode(Node *head, int x)
{
  ...
  return head;
}

并在 main 中更新它:

head = insertNode(head, 5);

另一种常见的做法是将指针传递给指针并直接更新它:

void insertNode(Node **head, int x)
{
   Node *temp;
   temp = new Node;
   temp->data = x;

   temp->next = *head;
   *head = temp;
}

然后这样调用它:

insertNode(&head, 5);

关于c++ - 链表问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3796010/

相关文章:

c++ - auto 变量作为函数参数仅适用于 > C++11

c++ - 为什么 MinGW-w64 浮点精度取决于 winpthreads 版本?

c++ - #在 C 中包含 iostream?

将结构元素与c中的整数进行比较

java - 将两个数字相加,并以反向链表形式存储

java - 无法在 Java 中创建 7M Long 类型变量的 LinkedList

c - 链接列表 - 切换元素

c++ - 在 OpenCv 中扩展轮廓

c++ - Visual C++ 2010 是否支持 C++11 线程库?

C - 无法释放链表结构中分配的内存