fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stdbool.h>
  4.  
  5. typedef struct sllist
  6. {
  7. int data;
  8. struct sllist *next;
  9. }
  10. sllnode;
  11.  
  12. // initially creating the first node of the Singly Linked List
  13. void create(sllnode *head, int elem)
  14. {
  15. head -> data = elem;
  16. head -> next = NULL;
  17. }
  18.  
  19. // inserting a node
  20. void insert( sllnode *head, int elem, int position )
  21. {
  22. if ( head == NULL )
  23. {
  24. printf("NULL returned \n");
  25. exit(0);
  26. }
  27. // this overrides the very first node if already created through create function
  28. if( position == 0 )
  29. {
  30. head -> data = elem;
  31. head -> next = NULL;
  32. }
  33. else
  34. {
  35. for ( int i = 0; i < position - 1; ++i )
  36. {
  37. head = head -> next;
  38. }
  39.  
  40. sllnode *new_node = malloc( sizeof(sllnode) );
  41. new_node -> data = elem;
  42. new_node -> next = NULL;
  43.  
  44. head -> next = new_node; // this is working here, unline the previous program I have shared. I am not using a pointer to pointer here. But it still works unline previous program.
  45. }
  46. }
  47.  
  48. // print the entire linked list
  49. void display(sllnode *head)
  50. {
  51. sllnode *temp = head;
  52. if ( head == NULL )
  53. {
  54. printf("NULL returned\n");
  55. exit(0);
  56. }
  57.  
  58. while( temp != NULL )
  59. {
  60. printf("%d \n", temp -> data);
  61. temp = temp -> next;
  62. }
  63. }
  64.  
  65.  
  66. // main function
  67. int main(void)
  68. {
  69. sllnode *head = malloc( sizeof(sllnode) );
  70. create(head,23);
  71. insert(head, 13, 0);
  72. insert(head, 15, 1);
  73. insert(head, 45, 2);
  74. display(head);
  75. }
  76.  
Success #stdin #stdout 0s 4340KB
stdin
Standard input is empty
stdout
13 
15 
45