'Can any one tell what is the error in this Linked list creation

Inside insert function head is not updating.

#include<iostream>

#include<stdlib.h>

using namespace std;

struct node {

    int data;
    struct node* next;
}*head = NULL;


void insert(struct node* head, int data) {

    struct node * newNode ;
    newNode->data = data;
    newNode->next = NULL;
    if (head == NULL) {
        head =newNode;
        
    }
    else {
        struct node* current = head;
        while (current->next != NULL) {
            current = current->next;
        }
        //newNode->next = NULL;
        current->next = newNode;
    }
    
}


void display(struct node * head) {

    struct node* current = head;
    while (current) {
        cout << current->data<<endl;
    }
}


int main()
{

    insert(head, 5);
    insert(head, 6);
    insert(head, 56);
    insert(head, 65);
    insert(head, 885);
    insert(head, 66);
    insert(head, 00);

    display(head);

}


Solution 1:[1]

The problem with the code is your head outside the scope of your function is still NULL. You have to define a pointer to this head in order to update it. Apart from that it is required to dynamically allocate memory for the newNode.

void insert(struct node** head, int data) {

    struct node * newNode = new node() ;
    newNode->data = data;
    newNode->next = NULL;
    if (*head == NULL) {
        *head = newNode;
    }
    else {
        struct node* current = *head;
        while (current->next != NULL) {
            current = current->next;
        }
        //newNode->next = NULL;
        current->next = newNode;
    }      
}

From main() call insert function as: insert(&head, 5);.

Another problem in your code is in display function, you're not updating current to current->next.

while (current) {
    cout << current->data << endl;
    current = current->next;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1