Inserting a node at the end of a linked list

#include <stdio.h>
#include <conio.h>

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

int main() {
  struct node* head = NULL;
  struct node* second = NULL;
  struct node* third = NULL;

  head = (struct node*)malloc(sizeof(struct node));
  second = (struct node*)malloc(sizeof(struct node));
  third = (struct node*)malloc(sizeof(struct node));

  head->data = 1;
  head->next = second;

  second->data = 2;
  second->next = third;

  third->data = 3;
  third->next = NULL;

  struct node* temp;
  temp = head;

  while (temp != NULL) { // for printing the linked list
    printf("%d ",temp->data);
    temp = temp->next;
  }

  struct node* new1;
  struct node* temp1;

  temp1 = head;

  while (temp1 != NULL) { // for traversing to the end
    temp1 = temp1->next;
  }

  new1 = (struct node*)malloc(sizeof(struct node));

  new1->data = 5;
  new1->next = NULL;

  temp1->next = new1;

  while (temp1 != NULL) { // again for printing the list
    printf("%d ",temp1->data);
    temp1 = temp1->next;
  }

  return 0;
}

      

I'm trying to insert a node at the end of my linked list, but it doesn't work. I created the linked list successfully, but I cannot insert a node at the end. My teacher taught me this, but it doesn't work.

+3


source to share


2 answers


As far as I understand, in the commented part

// for traversing to the end

      

the implementation is too repetitive; the condition should be



while ( temp1->next != NULL )

      

to terminate as soon as the last node is reached, not if the terminating pointer is reached NULL

.

+2


source


while(temp1 != NULL)          // for traversing to the end
{
    temp1 = temp1->next;
}

      

This will cycle before temp1

NULL

. You need to get the last node i.e. When temp1->next

is equal NULL

, for example



while(temp1->next != NULL)          // for traversing to the end
{
    temp1 = temp1->next;
}

      

+2


source







All Articles