-2

I am not able to add elements to the end of a single Linked List. I have tried looking other questions but I am not able to find a solution.

The code is:

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

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

void PushE(struct node** head,int data);

int main(){

  struct node* a = NULL;
  PushE(&a,3);
  PushE(&a,4);
}

void PushE(struct node** headRef, int data){


  struct node* current = *headRef;
  struct node* nNode;
  nNode = (struct node*)malloc(sizeof(struct node));
  nNode->data = data;
  nNode->next= NULL;

  if(current == NULL)
     current = nNode;
  else{
    while(current->next != NULL)
       current = current->next;

  current->next = nNode;
  }

}

Can anyone help me implement this.

Nithin krishna
  • 362
  • 1
  • 3
  • 12

2 Answers2

4

Problem is here:

if(current == NULL)
    current = nNode; // <--

How did you get current?

struct node* current = *headRef;

Current here is a copy of the pointer headRef pointed to!

You need to assign to *headRef directly.

Aconcagua
  • 24,880
  • 4
  • 34
  • 59
2

In this if statement

if(current == NULL)
   current = nNode;

there is changed local variable current. The pointer pointed to by head is not changed. So the original list will be unchanged after exiting the function.

The function can be declared and defined the following way

int PushE( struct node ** head, int data );

// ...

int PushE( struct node ** head, int data )
{
    struct node *nNode = malloc( sizeof( struct node ) );
    int success = nNode != NULL;

    if ( success )
    {
        nNode->data = data;
        nNode->next = NULL;

        while ( *head ) head = &( *head )->next;

        *head = nNode;
    }

    return success;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335