1

I have implemented a short linked list code to add to the beginning of the list.

However the head always contained NULL. I really couldn't get why its behaving in this way. Any help is appreciated ! Below is the code :

#include<stdio.h>
#include<stdlib.h>

typedef struct node
{
    int iData;
    struct node *next;
} Node;

void add2Beg(Node* head, int num);


int main(int argc, char const *argv[])
{
    Node *head = NULL;
    add2Beg(head, 5);
    if (head == NULL)
        printf("nothing in head !!!\n");
else{
    printf("not null\n");
}
    add2Beg(head, 15);
    return 0;
}

//adds to the beginning of the linked list
void add2Beg(Node* head, int num)
{
    //create a temporary location to hold the new entry
    Node* temp = (Node *)malloc(sizeof(Node));
    temp->iData = num;

    if(head == NULL)
    {
        head = temp;
        printf("inside add2Beg\n");
        printf("%d\n", head->iData);
        head->next = NULL;
        printf("exiting add2Beg\n");
    }
    else
    {
        temp->next = head;
        printf("%p\n", temp->next);
        head = temp;
    }

}
4

3 回答 3

6

因为head内部的变量add2Beg()是该函数的本地变量。给它分配一个新的指针值 ( head = temp;) 只会改变函数内部head的变量。您需要传入一个指向指针的指针:

void add2Beg(Node** head, int num)

然后*head在函数内部使用:

if(*head == NULL)
{
    *head = temp;

小心像这样的行head->next = NULL;- 这应该被重写为(*head)->next = NULL;or (**head).next = NULL;

等等。然后像这样调用函数:

add2Beg(&head, 15);
于 2012-09-20T19:05:13.547 回答
1

您的函数 add2beg 在修改时不会返回新的头。将您的功能更改为:

Node * add2Beg(Node* head, int num)

并在最后返回头部:

return head;
于 2012-09-20T19:05:56.287 回答
1

因为您从未将 head 分配给 NULL 以外的任何内容...

//here you set it to NULL then pass it to your function
Node *head = NULL; 
add2Beg(head, 5);

在您的函数中,您传入“head”的副本

void add2Beg(Node* head, int num)   
{
   //create a temporary location to hold the new entry   
    Node* temp = (Node *)malloc(sizeof(Node));   
    temp->iData = num;      
    if(head == NULL)     //we'll get in here

此时您将 temp 分配给它,因此在此函数的范围内它是无效的,但是一旦您离开此函数,它就会返回 NULL。

您传入了指针“head”的副本并将其称为“head”。您需要返回该值并将其分配给main()该函数,或者将指向 head 的指针传递给该函数,以便更新该值。

解决方案:

Node *head = NULL; 
head = add2Beg(head, 5);

Node* add2Beg(Node* head, int num){
    ...
    return head;

或者

Node *head = NULL; 
add2Beg(&head, 5);

void add2Beg(Node** head, int num){
    ...
于 2012-09-20T19:06:56.197 回答