2010-09-25 104 views
1

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

回答

4

您的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); 
0

你让你写入initNode函数的方式会导致内存泄漏。你已经传入了一个指针,但你需要传入一个指针的引用。 (同样的问题,詹姆斯和卡萨布兰卡提到insertNode。)