#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?
CodePudding user response:
As stated in comments: in midofLL()
:
Pointer
q
is declared but not assigned a value. Try:struct node *q = head, *p = head;
The first advance of
q
should also be an advance ofp
...p
"misses out" on the possible second advance ofq
... You'll be off a bit with your current logic... Gotta mind those 'P's & 'Q's...
CodePudding user response:
your problem is in this line struct node *q,*p=head;
as you initialized pointer called p but you didn't initialize the pointer q , so you made pointer q as a wild pointer which can make undefined behavior , the line you wrote is equivalent to writing :
struct node *q;
struct node *p = head;
so in order to not get confused , it's the best practice to separate the declaration of the variables , so do this :
struct node *q = head;
struct node *p = head;
instead of this struct node *q,*p=head;
and here is the fill edited code :
#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 = head;
struct node *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();
}