Manvendra Singh
Manvendra Singh

Reputation: 65

Inserting a node at the end of 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 am trying to insert a node at the end of my linked list, but it is not working. I created the linked list successfully but I am not able to insert a node at the end. This is what my teacher taught me, but it is not working.

Upvotes: 3

Views: 166

Answers (2)

Codor
Codor

Reputation: 17605

To my understanding, in the part that is commented

// for traversing to the end

the implementation iterates too far; the condition should be

while ( temp1->next != NULL )

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

Upvotes: 2

slugonamission
slugonamission

Reputation: 9642

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

This will loop until temp1 is NULL. You need to get the last node instead, i.e. when temp1->next is NULL, e.g.

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

Upvotes: 2

Related Questions