Facebook
From Denim Tapir, 3 Years ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 48
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. struct Node
  4. {
  5.     int data;
  6.     struct Node* next;
  7. };
  8. void push(struct Node **head_ref, int new_data)
  9. {
  10.     struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
  11.     new_node->data = new_data;
  12.     new_node->next = (*head_ref);
  13.     (*head_ref) = new_node;
  14. }
  15. void printMiddle(struct Node *head)
  16. {
  17.     struct Node *slow_ptr = head;
  18.     struct Node *fast_ptr = head;
  19.     if (head!=NULL)
  20.     {
  21.         while (fast_ptr != NULL && fast_ptr->next != NULL)
  22.         {
  23.             fast_ptr = fast_ptr->next->next;
  24.             slow_ptr = slow_ptr->next;
  25.         }
  26.         printf("The middle element is [%d]\n\n", slow_ptr->data);
  27.     }
  28. }
  29. int main()
  30. {
  31.     struct Node* head = NULL;
  32.     push(&head, 1);
  33.     push(&head, 2);
  34.     push(&head, 3);
  35.     push(&head, 4);
  36.     push(&head, 5);
  37.     push(&head, 6);
  38.     push(&head, 7);
  39.     printMiddle(head);
  40.     return 0;
  41. }