C program to create a linear linked list

The program shown below first allocates a block of memory dynamically for the first node using the statement

head = (node *)malloc(sizeof(node));

which returns a pointer to a structure of type node that has been type defined earlier. The linked list is then created by the function create. The function requests for the number to be placed in the current node that has been created. If the value assigned to the current node is –999, then null is assigned to the pointer variable next and the list ends. Otherwise, memory space is allocated to the next node using again the malloc function and the next value is placed into it. Not that the function create calls itself recursively and the process will continue until we enter the number –999.

The items stored in the linked list are printed using the function print which accept a pointer to the current node as an argument. It is a recursive function and stops when it receives a NULL pointer. Printing algorithm is as follows;

1. Start with the first node.
2. While there are valid nodes left to print
a) print the current item and
b) advance to next node

Similarly, the function count counts the number of items in the list recursively and return the total number of items to the main function. Note that the counting does not include the item –999 (contained in the dummy node).

Program to create a linked lis


  1. #include
  2. #include
  3. #define NULL 0

  4. struct linked_list
  5. {

  6. int
    number;

  7. struct
    linked_list *next;
  8. };
  9. typedef struct linked_list node;
  10. main()
  11. {

  12. node *head;

  13. void
    create(node *p);

  14. int
    count(node *p);

  15. void print(node *p);

  16. head = (node *)
    malloc(sizeof(node));

  17. create(head);

  18. printf("\n");

  19. printf(head);

  20. printf("\n");

  21. printf("\n Number of items = %d \n", count(head));
  22. }
  23. void create(node *list)
  24. {

  25. printf("Input a number\n");

  26. printf("(type -999 at end): ");

  27. scanf
    ("%d", &list -> number);


  28. if
    (list->number == -999)

  29. {

  30. list->next = NULL;

  31. }

  32. else /*create next node */

  33. {

  34. list->next = (node *)malloc(sizeof(node));

  35. create(list->next);

  36. }

  37. return;
  38. }
  39. void print(node *list)
  40. {

  41. if(list->next != NULL)

  42. {

  43. printf("%d-->",list ->number);

  44. if(list->next->next == NULL)

  45. printf("%d", list->next->number);


  46. printf
    (list->next);

  47. }

  48. return
    ;

  49. }


  50. int
    count(node *list)

  51. {

  52. if
    (list->next == NULL)

  53. return
    (0);

  54. else

  55. return(1+ count(list->next));

  56. }




Post a Comment

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post