Google Add

Search

Write a C Program to Insert a Node at the Head/Beginning of a Linked List


In my previous post, i mentioned the advantage of linked list. In this post i am showing how to insert a node at the beginning of a linked list.


Program to Insert a Node at the Head/Beginning of a Linked List

// Program

#include <stdlib.h>
#include <stdio.h>
// Declare the Node

struct Node{

        int data;
        struct Node* next;
        };  

struct Node* head;        
// Insert the node a the beginning of a linked list

void insert(int data){

        struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
        temp->data = data;
        temp->next = head;
        head = temp;

}

void print(){

        struct Node* temp = head;
    
        while(temp!=NULL)
        {   
             printf("%d",temp->data);
             temp = temp->next;
             printf("\n");
        }   
}

int main()
{

        head = NULL;
        insert(4);
        insert(5);
        insert(6);
        print();
}


3 comments:

  1. in this code display works fine but there is something wrong in its display when i restrict the function to insert at the beginning
    #include
    #include

    struct node
    {
    int info;
    struct node *link;
    }*head,*temp,*temp1;

    void Insert();
    void Display();

    void main()
    {
    int ch;
    clrscr();
    head=NULL;
    while(1)
    {
    printf("\nEnter your choise:\n1.Insert\n2.Display\n3.Exit\nYour Choise:");
    scanf("%d",&ch);
    switch(ch)
    {
    case 1:Insert();
    break;
    case 2:Display();
    break;
    case 3:exit(0);
    break;
    default:
    printf("\nWrong Choise!\n");
    }
    }
    getch();
    }

    void Insert()
    {
    int x;
    printf("Enter the value to be inserted:");
    scanf("%d",&x);

    temp=(struct node *)malloc(sizeof(struct node));
    temp->info=x;
    temp->link=NULL;

    temp1=head;
    while(temp1->link!=NULL)
    temp1=temp1->link;
    temp1->link=temp;
    }

    void Display()
    {
    temp1=head;
    printf("List is:");
    while(temp1->link!=NULL)
    {
    temp1=temp1->link;
    printf("%d ",temp1->info);
    }
    printf("\n");
    }





    ReplyDelete
  2. simple nd excellent

    ReplyDelete