fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. // A linked list node
  5. struct node
  6. {
  7. int data;
  8. struct node *next;
  9. };
  10.  
  11.  
  12. void push(struct node** head, int new_data)
  13. {
  14. /* 1. allocate node */
  15. struct node* new_node = (struct node*) malloc(sizeof(struct node));
  16.  
  17. /* 2. put in the data */
  18. new_node->data = new_data;
  19.  
  20. /* 3. Make next of new node as head */
  21. new_node->next = *head;
  22.  
  23. /* 4. move the head to point to the new node */
  24. *head = new_node;
  25. }
  26.  
  27. /* Given a node prev_node, insert a new node after the given prev_node */
  28. void insertAfter(struct node** prev_node, int new_data)
  29. {
  30. /*1. check if the given prev_node is NULL */
  31. if (*prev_node == NULL)
  32. {
  33. printf("the given previous node cannot be NULL");
  34. return;
  35. }
  36.  
  37. /* 2. allocate new node */
  38. struct node* new_node =(struct node*) malloc(sizeof(struct node));
  39.  
  40. /* 3. put in the data */
  41. new_node->data = new_data;
  42.  
  43. /* 4. Make next of new node as next of prev_node */
  44. new_node->next = (*prev_node)->next;
  45.  
  46. /* 5. move the next of prev_node as new_node */
  47. (*prev_node)->next = new_node;
  48. }
  49.  
  50.  
  51. void append(struct node** head, int new_data)
  52. {
  53. /* 1. allocate node */
  54. struct node* new_node = (struct node*) malloc(sizeof(struct node));
  55.  
  56. struct node *last = *head;
  57.  
  58. /* 2. put in the data */
  59. new_node->data = new_data;
  60.  
  61. /* 3. This new node is going to be the last node, so make next of it as NULL*/
  62. new_node->next = NULL;
  63.  
  64. /* 4. If the Linked List is empty, then make the new node as head */
  65. if (*head == NULL)
  66. {
  67. *head = new_node;
  68. return;
  69. }
  70.  
  71. /* 5. Else traverse till the last node */
  72. while (last->next != NULL)
  73. last = last->next;
  74.  
  75. /* 6. Change the next of last node */
  76. last->next = new_node;
  77. return;
  78. }
  79.  
  80. // This function prints contents of linked list starting from the given node
  81. void printList(struct node *node)
  82. {
  83. while (node != NULL)
  84. {
  85. printf(" %d ", node->data);
  86. node = node->next;
  87. }
  88. }
  89.  
  90. /* Driver program to test above functions*/
  91. int main()
  92. {
  93. /* Start with the empty list */
  94. struct node* head = NULL;
  95.  
  96.  
  97. append(&head, 6);
  98. push(&head, 7);
  99. push(&head, 1);
  100. append(&head, 4);
  101. insertAfter(&head->next, 8);
  102. printf("\n Created Linked list is: ");
  103. printList(head);
  104.  
  105. return 0;
  106. }
Success #stdin #stdout 0s 2384KB
stdin
Standard input is empty
stdout
 Created Linked list is:  1  7  8  6  4