Click here to Skip to main content
15,896,557 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Programming Problems and Competitions :: HackerRank[^]

What I have tried:

C++
/*
  Insert Node at the end of a linked list 
  head pointer input could be NULL as well for empty list
  Node is defined as 
  struct Node
  {
     int data;
     struct Node *next;
  }
*/
Node* Insert(Node *head,int data)
{
  // Complete this method
    Node *temp;
    temp=head;
    if(temp=='\0'){
        temp=(struct Node *)malloc(sizeof(struct Node));
        temp->data=data;
        head=temp;
        head->next='\0';
    }
        
     else {
            while (temp!='\0'){
                temp=temp->next;
            }
        temp->data=data;
        temp->next='\0';
    }
    
    return head;
}
Posted
Updated 30-Dec-16 1:37am
v2
Comments
Patrice T 30-Dec-16 6:57am    
And you plan to tell us what is the problem ?

1 solution

Quote:
else {
while (temp!='\0'){
temp=temp->next;
}
temp->data=data;
temp->next='\0';
}

Should be, instead
else 
{
  while ( temp->next )
  {
    temp = temp->next;
  }
  temp->next = (struct Node *)malloc(sizeof(struct Node));
  temp->next->data = data;
  temp->next->next = NULL;
}




Please note, in C++ code, use:
  • nullptr (instead of '\0' or NULL.)
  • new instead of malloc.
  • Node constructor to initialize it.


At least, if you insist using C-like programming, always check the return value of malloc.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900