Linkedklist insert at begining in c

/*createtor sarkarsumit.blogspot.com*/

#include<stdio.h>
#include<stdlib.h>

struct node
{
    int data;
    struct node *next;

};
typedef struct node node;
//functionto create a linked list
node * createLinkedlist(int n);
void display(node *start);
node *insertBeg(node *head);

int main()
{
    int n=0;
    node *head=NULL;
    node * HEAD =NULL; //address of first node
    printf("ENter Number of nodes : ");
    scanf("%d",&n);
    HEAD = createLinkedlist(n);
    display(HEAD);
    HEAD=insertBeg(HEAD);
    display(HEAD);
    return 0;
}

node *createLinkedlist(int n)
{
    int i=0;
    node *head=NULL;
    node *temp=NULL;
    node *p = NULL;

    for(i=0;i<n;i++)
    {
        //create indibidual isolated nodes
        temp=(node*)malloc(sizeof(node));
        printf("enter data for %d",(i+1));
        scanf("%d",&temp->data);
        temp->next=NULL;

        if(head==NULL)
        {
            head= temp; //make temp as first node. created individually

        }
        else
        {
            p=head;
            while(p->next !=NULL)
            {
                p=p->next;


            }
            p->next=temp;

        }
    }
    return head;
}

void display(node *start)
{
    node *p = start;
    while(p  != NULL)
    {
        printf("%d\n",p->data);
        p=p->next;
    }
}

node *insertBeg(node *head)
{

    node *ptr;

    if(head==NULL)
    {
        head=(node*)malloc(sizeof(node));
        printf("\nEnter data :");
        scanf("%d",&head->data);
        head->next=NULL;

    }
    else
    {
        ptr=(node*)malloc(sizeof(node));
        printf("\nEnter data :");
        scanf("%d",&ptr->data);
        ptr->next=head;
    }
    return  ptr;
}


Comments

Popular posts from this blog

Blogging Website using Python-flask,MySql,Bootstrap 4

calculator in java with actionListener and KeyListener