Monday 10 October 2016

c program to insert a node in the beginning of the linked list

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

     struct Node{
     int data;
     struct Node *next;
     };
     struct Node* head;

     void Insert(int x)
     {
     struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
     temp->data=x;
     temp->next = head;    
     head= temp;           
     }


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

    
     int main()
     {   
      head =NULL;

      int n, i, x;
    
     printf("How many Numbers?: \n");
     scanf("%d", &n);

     for(i= 0; i<n; i++)
     {
    printf("Enter the number: ");
    scanf("%d",&x);
     Insert(x);
    Print();
      }
      return 0;

     }

No comments:

Post a Comment