c - 简单链表

标签 c data-structures linked-list

我有以下单链表,我总是得到长度为 1,即使我压入 3 个元素,也总是只创建一个节点。请帮助。谢谢。

#include <stdio.h>

struct node
{
    int data;
    struct node *next;

};

void push(struct node **head,int data)
{
    struct node *temp = (struct node*)malloc(sizeof(struct node));
    temp->data=data;
    if(*head == NULL)
    {
        *head=temp;

    }
    else
    {
    temp->next=*head;
    *head=temp;

    }
}

int length(struct node *head)
{
    struct node *temp = head;
    int count=0;
    if(temp !=NULL)
    {
        count++;
        printf("%d",temp->data);
        temp=temp->next;
    }
    return count;
}
int main()
{
    int a;
    struct node *head=NULL;
    push(&head,1);
    push(&head,2);
    push(&head,3);

    a=length(head);
    printf("%d",a);
    return 0;
}

最佳答案

将长度函数中的if替换为while

关于c - 简单链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7396764/

相关文章:

c - 数组作为 c 中的参数和输入

c - Linux内核: What kind of C Linux kernel is using?

algorithm - 最小的硬币变化(有限供应)具有更好的时间复杂度讨论

c# - 将有向无环图 (DAG) 转换为树

C 二维链表

c++ - 带有随机指针的链表的深拷贝

c - 在c中排序双向链表

c - 了解声明数组长度

c# - 在没有数据库的情况下存储联系人/地址类型信息的最佳格式是什么?

c - 为什么我不能像这样初始化数组?