Advertisement
mhrabbi

Find the middle element of a linked list

Oct 21st, 2019
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.24 KB | None | 0 0
  1. #include<stdio.h>
  2.  
  3. struct node
  4. {
  5.     int data;
  6.     struct node *next;
  7. }*head;
  8.  
  9. int main()
  10. {
  11.     int n,mid;
  12.     printf("Enter total number of node: ");
  13.     scanf("%d",&n);
  14.  
  15.     createList(n);
  16.  
  17.     printf("\nList is\n ");
  18.  
  19.     displaylist();
  20.  
  21.     mid=findmid();
  22.  
  23.     printf("\nMiddle of the element is %d: ",mid);
  24.  
  25.     return 0;
  26. }
  27. void createList(int n)
  28. {
  29.     struct node *p,*temp;
  30.     int i,data;
  31.  
  32.     temp=(struct node *)malloc(sizeof(struct node));
  33.  
  34.     printf("Enter the data of the node 1: ");
  35.     scanf("%d",&data);
  36.  
  37.     temp->data=data;
  38.     temp->next=NULL;
  39.  
  40.     p=temp;
  41.     head=temp;
  42.  
  43.     for(i=2; i<=n; i++)
  44.     {
  45.         temp=(struct node *)malloc(sizeof(struct node));
  46.  
  47.         printf("Enter the data of the node %d: ",i);
  48.         scanf("%d",&data);
  49.  
  50.         temp->data=data;
  51.         temp->next=NULL;
  52.  
  53.         p->next=temp;
  54.         p=p->next;
  55.  
  56.     }
  57.  
  58. }
  59.  
  60. void displaylist()
  61. {
  62.     struct node *temp;
  63.     temp=head;
  64.  
  65.     while(temp!=NULL)
  66.     {
  67.         printf("\n%d",temp->data);
  68.         temp=temp->next;
  69.     }
  70. }
  71. int findmid()
  72. {
  73.     struct node *p,*q;
  74.     p=head;
  75.     q=head;
  76.  
  77.     while(q && q->next)
  78.     {
  79.         p=p->next;
  80.         q=q->next->next;
  81.     }
  82.     return p->data;
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement