Advertisement
rifat99

new node at the beginning of a Singly Linked List.

Feb 16th, 2019
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.91 KB | None | 0 0
  1. //Write a program in C to insert new node at the beginning of a Singly Linked List.
  2.  
  3.  
  4. #include<stdio.h>
  5. #include<stdlib.h>
  6. typedef struct Node
  7. {
  8.     int x;
  9.     struct Node *ptr;
  10. }node;
  11.  
  12. node *head = NULL;
  13.   node *temp = NULL;
  14.  
  15. int main()
  16. {
  17.     int i,n;
  18.      printf("Input the number of nodes:",n);
  19.     scanf("%d",&n);
  20.  
  21.     for(i=1; i<=n; i++)
  22.     {
  23.         node *q = (node*)malloc(sizeof (node));
  24.  
  25.          printf("\nInput data for node %d : ",i);
  26.  
  27.         scanf("%d", &q -> x);
  28.  
  29.         q -> ptr = NULL;
  30.         if(head == NULL)
  31.         {
  32.             head = q;
  33.         }
  34.         else
  35.         {
  36.             q -> ptr = head;
  37.             head = q;
  38.  
  39.  
  40.     }
  41.     }
  42.  
  43.  
  44.       node *temp = head;
  45.  
  46.       printf("\nData entered in the list : \n");
  47.  
  48.       while(temp!= NULL)
  49.         {
  50.  
  51.             printf("\nData = %d\n", temp->x);
  52.             temp = temp->ptr;
  53.         }
  54.     return 0;
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement