我对链表的实现没有打印出任何内容

时间:2019-12-23 14:31:40

标签: c data-structures struct linked-list singly-linked-list

我已经在下面的代码中实现了链表,但是它没有输出任何内容。在代码中,我添加了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;
}

1 个答案:

答案 0 :(得分:0)

此声明

head=temp;
函数iinsert_node中的

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

您没有使用函数insert_head的返回值。您必须至少写成

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' );
}
相关问题