链接列表问题

时间:2010-09-25 23:41:39

标签: c++ linked-list

我在编写链表时遇到了一些问题。我不知道如果它是我的插入函数的问题,或者它是我的遍历函数是不正确的。我希望得到一些意见。旁注,我现在正在主要列表中,因为我不知道我的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;
}

2 个答案:

答案 0 :(得分:4)

您的head未从main返回insertNode。请注意,即使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);

答案 1 :(得分:0)

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