Ajay Khetan
Ajay Khetan

Reputation: 455

Program inserting an element in single 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);

}

The above is a code for inserting element in the begining of the single linked link list in c.

The code compiles successfuly but when i am trying to insert an element the system hangs up... Not to locate the error. Can anyone suggest the correction i need to done.

Is there any error in the expression mentioned below... Need help.

p=insert_beg(p,a);

Upvotes: 0

Views: 386

Answers (3)

Ravi varu
Ravi varu

Reputation: 69

#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);

}

Upvotes: 1

Paul Ogilvie
Paul Ogilvie

Reputation: 25296

    while(t->next!=NULL)

should be:

    while(t!=NULL)

also, your insert function can be simplified to:

struct node* insert_beg(struct node *h,int x)
{
    struct node *t;
    t=(struct node *)malloc(sizeof(struct node));
    t->data=x;
    t->next=h;
    return t;
}

Upvotes: 0

pbn
pbn

Reputation: 2706

You have an error in:

printf("\n address = %u --- ",*h);

Trying to print an entire structure.

In general use a debbuger for this as explained here

You can compile your program with debug information as follows:

gcc -o main -g main.c

And run it in gdb:

gdb main

Type 'run' command inside gdb, if it fails you can use a 'backtrace' to get loads of information why. Get comfortable with gdb tutorials as the manual might scare you off at first.

Upvotes: 0

Related Questions