fork download
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3.  
  4. /* Link list node */
  5. struct Node
  6. {
  7. int data;
  8. struct Node* next;
  9. };
  10.  
  11. /* Function to get the middle of the linked list*/
  12. void printMiddle(struct Node *head)
  13. {
  14. struct Node *slow_ptr = head;
  15. struct Node *fast_ptr = head;
  16.  
  17. if (head!=NULL)
  18. {
  19. while (fast_ptr->next!= NULL && fast_ptr->next->next != NULL)
  20. {
  21. fast_ptr = fast_ptr->next->next;
  22. slow_ptr = slow_ptr->next;
  23. }
  24. printf("The middle element is [%d]\n\n", slow_ptr->data);
  25. }
  26. }
  27.  
  28. void push(struct Node** head_ref, int new_data)
  29. {
  30. /* allocate node */
  31. struct Node* new_node =
  32. (struct Node*) malloc(sizeof(struct Node));
  33.  
  34. /* put in the data */
  35. new_node->data = new_data;
  36.  
  37. /* link the old list off the new node */
  38. new_node->next = (*head_ref);
  39.  
  40. /* move the head to point to the new node */
  41. (*head_ref) = new_node;
  42. }
  43.  
  44. // A utility function to print a given linked list
  45. void printList(struct Node *ptr)
  46. {
  47. while (ptr != NULL)
  48. {
  49. printf("%d->", ptr->data);
  50. ptr = ptr->next;
  51. }
  52. printf("NULL\n");
  53. }
  54.  
  55. /* Drier program to test above function*/
  56. int main()
  57. {
  58. /* Start with the empty list */
  59. struct Node* head = NULL;
  60. int i;
  61.  
  62. for (i=5; i>0; i--)
  63. {
  64. push(&head, i);
  65. printList(head);
  66. printMiddle(head);
  67. }
  68.  
  69. return 0;
  70. }
  71.  
Success #stdin #stdout 0s 16048KB
stdin
Standard input is empty
stdout
5->NULL
The middle element is [5]

4->5->NULL
The middle element is [4]

3->4->5->NULL
The middle element is [4]

2->3->4->5->NULL
The middle element is [3]

1->2->3->4->5->NULL
The middle element is [3]