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