我写的链表有问题。我不知道是我的插入函数有问题,还是我的遍历函数不正确。我希望有一些意见。旁注,我现在正在 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/