【问题标题】:my implementation of linked list doesn't print out anything我的链表实现没有打印出任何东西
【发布时间】:2019-12-23 14:31:40
【问题描述】:

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

【问题讨论】:

  • 你想要什么输出:“0 1 2 3”还是“3 2 1 0”?
  • 我的意思是“3 2 1 0”。函数名是插入到头部

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


【解决方案1】:

此声明

head=temp;

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

您没有使用函数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' );
}

【讨论】:

  • 你能解释一下为什么函数 insert_head 必须返回临时变量然后分配给 head 吗?我以为函数 insert_head 已经将 temp 分配给 head 了?
  • 我认为 head 是一个指针,所以如果我将 head 的地址传递给函数,它可以改变它的值?我了解到将任何变量的地址传递给函数可以在全局范围内更改其值,不是吗?
  • @Becker 您正在尝试更改指针本身的值,而不是指针指向的对象(由存储的值寻址)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-09
  • 2016-03-25
  • 1970-01-01
相关资源
最近更新 更多