0

I have written this code to insert node at the end of singly linked-list. It compiles without errors but upon execution no output shows. Where have i gone wrong?

void insert_n(int x){
node* temp1 = new node();
temp1->data=x;
temp1->next=NULL;
node* temp2 = head;
while(temp2->next!=NULL){
    temp2 = temp2->next;
}
temp2->next=temp1;
}

void print(){
node* temp = head;
while(temp!=NULL){
    cout<<temp->data<<" ";
    temp = temp->next;
}
}

int main()
{
    head = NULL;
    insert_n(2);
    insert_n(3);
    insert_n(4);
    insert_n(5);
    print();
    return 0;
}

Does it fail because there should be a special case for when the list is empty?

  • 1
    Whatever `head` is, there are zero write accesses to it in `insert_n`. So, whatever that function does, it cannot change the thing that `print` accesses. On a related note, `temp2->next` is invalid if `temp2` is a null pointer, which it initially is. You should get a segmentation fault there. – bitmask Jun 16 '20 at 07:03

3 Answers3

2

Yes, You are right. If head == NULL then your insert function can't work. Following is the correction of your insert_n() function:

void insert_n(int x) {
  node* temp1 = new node();
  temp1->data = x;
  temp1->next = NULL;
  if (head == NULL) {
    head = temp1;
  } else {
    node* temp2 = head;
    while (temp2->next != NULL) {
      temp2 = temp2->next;
    }
    temp2->next = temp1;
  }
}

Here is a code example: C Program to Search and insert in a singly Linked List

Ismail H Rana
  • 351
  • 1
  • 9
1

Your head is never set to any defined value and so it failes at:

node* temp2 = head;
while(temp2->next!=NULL){

because head is NULL and so temp2 is also NULL, which results in a segmentation fault, when it tries to access next.

Tobias
  • 543
  • 1
  • 3
  • 15
-2

Try this:

#include <iostream>

using namespace std; // this was missing !!!

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

struct node *head;

void insert_n(int x) {
    node* temp1 = new node();
    temp1->data = x;
    temp1->next = NULL;
    node* temp2 = head;
    while (temp2->next != NULL) {
        temp2 = temp2->next;
    }
    temp2->next = temp1;
}

void print() {
    node* temp = head;
    while (temp != NULL) {
        cout << temp->data << " ";
        temp = temp->next;
    }
}

int main()
{
    head = new node(); // without this you get a crash !!!
    insert_n(2);
    insert_n(3);
    insert_n(4);
    insert_n(5);
    print();
    return 0;
}
user2380383
  • 174
  • 1
  • 8