#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node * next;
}*head=NULL;
void create(int A[],int n){
struct node* last,*t;
head=(struct node *)malloc(sizeof(struct node));
head->data = A[0];
head->next=NULL;
last = head;
for(int i=1;i<n;i++){
t=(struct node *)malloc(sizeof(struct node));
t->data = A[i];
last->next=t;
t->next = NULL;
last= t;
}
}
void display(struct node *p){
while(p!=NULL){
printf("%d ",p->data);
p=p->next;
}
}
void midofLL(){
struct node *q,*p=head;
while(q!=NULL){
q=q->next;
if(q) q=q->next;
if(q) p=p->next;
}
printf("%d",p->data);
}
int main()
{
int A[]={2,3,6,7,8};
create(A,5);
display(head);
printf("\n");
midofLL();
}
I am finding the middle node in a singly liked list using two pointers p and q .q incremented by 2 nodes,p incremented by 1 node. What is the error in this ? Only the linked list is getting printed.I need the data stored in middle element. How to correct my code?