-1
#include <stdio.h>
#include <stdlib.h>

struct node {
  int data;
  struct node *next;
};

void insertEnd(struct node *l,int val) {
  struct node *temp=(struct node*)malloc(sizeof(struct node));
  temp->data=val;
  temp->next=NULL;
  if (l==NULL) l=temp;
  struct node* p=l;
  while (p->next!=NULL) p=p->next;
  p->next=temp;
}

void display(struct node *l) {
  struct node *p=l;
  if (p==NULL) printf("Empty list");
  while (p!=NULL) {
    printf("%d ",p->data);
    p=p->next;
  }
}

int main() {
  struct node *l=NULL;
  insertEnd(l,4);
  insertEnd(l,5);
  insertEnd(l,6);
  insertEnd(l,7);
  display(l);
}

This is a very basic code for creating a linked list by inserting elements from the end and displaying it. But this keeps displaying empty list and i can't understand why. please help me out

varsha
  • 1
  • 1
  • 1
    Does this answer your question? [Pointer to pointer clarification](https://stackoverflow.com/questions/21604946/pointer-to-pointer-clarification) – Yunnosch Oct 15 '21 at 09:47
  • 1
    You give a copy of NULL as parameter to `insertEnd()`. After executing the function, it will still be NULL. See the proposed duplicate about how to solve that with pointer to pointer concept. – Yunnosch Oct 15 '21 at 09:49

1 Answers1

0

In main(), struct node pointer l is initialised with NULL. When you pass l to insertEnd(), you are actually passing NULL. If you want to make changes to pointer in another function, pass the address of pointer. You should do

void insertEnd(struct node **l,int val) {
  .....
  if (*l==NULL) *l=temp;
  struct node* p=*l;
  .....
}
    
int main() {
  struct node *l=NULL;
  // pass the address of l to insertEnd()
  insertEnd(&l,4);
  insertEnd(&l,5);
  .....
}

Even after making above changes, you code will not work fine because there is one more problem in your insertEnd(). When inserting the first node to list, it end up creating circular list i.e. the next of the first node point to itself. This is happening due to this part of insertEnd():

  // Assuming that first parameter of insertEnd() can receive 'struct node *'
  // address i.e. insertEnd(struct node **l, .....)

  if (*l==NULL) *l=temp;
  struct node* p=*l;
  while (p->next!=NULL) p=p->next;
  p->next=temp;

When first node will be inserted, list head will point to temp, then p will be initialised with list head and while loop condition (pp->next!=NULL) will be false and p->next will be assigned to temp i.e. to itself.

So, when the insertEnd() called to insert second node to list the while loop loops forever in circular list. The insertion at the end of list should be in else part of if (l==NULL) which is missing in your code. It should be like this

  if (*l==NULL) {
    *l=temp;
  } else {
    struct node* p=*l;
    while (p->next!=NULL) p=p->next;
    p->next=temp;
  }
H.S.
  • 11,654
  • 2
  • 15
  • 32