我的链表实现没有打印出任何东西

my implementation of linked list doesn't print out anything

我已经在下面的代码中实现了链表,但是它没有打印出任何东西。在代码中我添加了 3 个节点。有人请告诉我我哪里错了。感谢您的帮助。

#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
    int value;
    struct Node *next;
}node;

node* insert_head(node *head, int value){
    node *temp;
    temp=(struct Node*)malloc(sizeof(struct Node));
    temp->value=value;
    if (head==NULL)
    {
        head=temp;
    }
    else{
        temp->next=head;
        head=temp;
    }
    return temp;
}

void printlist(node *head){
    node *p=head;
    while (p->next!=NULL)
    {
        printf("%d", p->value);
        p=p->next;
    }
}

int main(){
    node *head;
    head=(struct Node *)malloc(sizeof(struct Node));
    head->value=0;
    head->next=NULL;
    insert_head(head, 1);
    insert_head(head, 2);
    insert_head(head, 3);
    printlist(head);
    return 0;
}

此声明

head=temp;

在函数内 iinsert_node 没有意义,因为在函数内更改了它的局部变量 head,它是原始参数 head 的副本。更改变量的副本不会影响原始变量的存储值。

您没有使用函数 insert_head 的 return 值。你至少要写成

head = insert_head(head, 1);

或更安全

node *temp = insert_head(head, 1);

if ( temp != NULL ) head = temp;

函数内的if语句

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

是多余的。该函数看起来像

node* insert_head(node *head, int value){
    node *temp = malloc( sizeof( node ) );

    if ( temp != NULL )
    {
        temp->value = value;
        temp->next = head;
    }

    return temp;
}

而函数 printlist 通常具有未定义的行为,因为 head 可以等于 NULL。改写成

void printlist(node *head){
    for ( ; head != NULL; head = head->next )
    {
        printf("%d ", head->value);
    }
    putchar( '\n' );
}