C++ 链表问题

C++ 链表问题,c++,linked-list,C++,Linked List,我写的链表有点问题。我不知道是我的insert函数出了问题,还是我的遍历函数出了问题。我希望得到一些意见。另外,我现在正在初始化main中的列表,因为我不知道initNode函数是否正确 #include <iostream> using namespace std; typedef struct Node { int data; Node *next; }; void initNode(Node *head) { head = new Node; he

我写的链表有点问题。我不知道是我的insert函数出了问题,还是我的遍历函数出了问题。我希望得到一些意见。另外,我现在正在初始化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;
}
#包括
使用名称空间std;
定义表结点
{
int数据;
节点*下一步;
};
void initNode(节点*头)
{
头=新节点;
head->next=NULL;
}
void insertNode(节点*head,int x)
{
节点*温度;
temp=新节点;
温度->数据=x;
温度->下一步=头部;
压头=温度;
}
空心导线测量(节点*头部)
{
节点*温度;
温度=水头;
if(head==NULL)
{

cout编写initNode函数的方式将导致内存泄漏。您已传入指针,但需要传入指针的引用。(与James和casablanca在insertNode中提到的问题相同。)

编写initNode函数的方式将导致内存泄漏。您已传入指针,但需要传入指针引用。(与James和casablanca在insertNode中提到的问题相同。)

您的
不会从
插入节点
返回到
。请注意,即使
是一个指针,指针本身也是一个值,对指针值的任何更改都不会反映在
中。最简单的解决方案是传回
的更新值:

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);

您的
head
不会从
insertNode
返回到
main
。请注意,即使
head
是一个指针,指针本身也是一个值,对指针值的任何更改都不会反映在
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);