c - 程序在单链表中插入一个元素

标签 c data-structures linked-list

#include<stdio.h>
#include<malloc.h>
struct node
{
    int data;
    struct node *next;
};
struct node* insert_beg(struct node *h,int x)
{
    struct node *t;
    printf("\n address = %u --- ",*h);
    t=(struct node *)malloc(sizeof(struct node));
    if(h==NULL)
    {
        t->data=x;
        t->next=NULL;
        h=t;
    }
    else
    {


        t->data=x;
        t->next=h;
        h=t;
    }
    return h;

}
void display(struct node *h1)
{
    struct node *t=h1;
    while(t->next!=NULL)
    {
        printf("%d->",t->data);
        t=t->next;
    }
}
int main()
{
    struct node *p=NULL;
    int a,ch=5;
    while(ch--)
    {

    printf("\n Enter data");
    scanf("%d",&a);
    p=insert_beg(p,a);
    display(p);
    }display(p);

}

以上是c中单链表开头插入元素的代码。

代码编译成功,但是当我尝试插入元素时系统挂起......无法找到错误。谁能建议我需要做的更正。

下面提到的表达式是否有错误...需要帮助。

p=insert_beg(p,a);

最佳答案

#include<stdio.h>
#include<malloc.h>
struct node
{
    int data;
    struct node *next;
};
struct node* insert_beg(struct node *h,int x)
{
    struct node *t;
    t=(struct node *)malloc(sizeof(struct node));
    if(h==NULL)
    {
        t->data=x;
        t->next=NULL;
        h=t;
    }
    else
    {
        t->data=x;
        t->next=h;
        h=t;
    }
    return h;
}
void display(struct node *h1)
{
     struct node *t=h1;
     while(t->next!=NULL)
     {
         printf("%d->",t->data);
         t=t->next;
     }
    printf("%d",t->data);
}
int main()
{
    struct node *p=NULL;
    int a,ch=5;
    while(ch>=0)
    {
        printf("\n Enter data:-");
        scanf("%d",&a);
        p=insert_beg(p,a);
        display(p);
        ch--;
    }
    display(p);

}

关于c - 程序在单链表中插入一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41225854/

相关文章:

c++ - 如何在内存中的位图上绘制文字[无MFC]

c - Openssl BIO_read 不返回

c++ - 链表节点类中的链接数

c++ - 从单链表中删除特定值?

c++ - SOCI 的问题

c - 这个 "alarm"错误是什么意思?

python - 3D 数据的最佳数据结构?

.net - 存储由 3 元组索引的对象的最佳数据结构,以便沿每个维度和低内存配置进行快速检索?

java - 优先队列中的元素何时排序?

Java - 这个对象什么时候卸载?