C++ 链表问题
我写的链表有点问题。我不知道是我的insert函数出了问题,还是我的遍历函数出了问题。我希望得到一些意见。另外,我现在正在初始化main中的列表,因为我不知道initNode函数是否正确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
#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);