-2

My Cpp File code

#include <bits/stdc++.h>
using namespace std;

class Node
{
public:
    int data;
    Node *next;
};

void insert_at_end(Node *head, int data)
{
    Node *temp = new Node();
    temp->data = data;
    temp->next = NULL;

    if (head == NULL)
    {
        head = temp;
        // cout << temp->data << " " << " : " << head->data << endl ;
    }
    else
    {
        Node *last = head;
        while (last->next != NULL)
        {
            last = last->next;
        }
        last->next = temp;
        cout << "Inserted " << data << " at the End \n";
    }
}


void printList(Node *head)
{
    cout << "List : \n";
    Node *temp = head;
    if (temp == NULL)
        cout << "Forgive me !";
    while (temp != NULL)
    {
        cout << "\t" << temp->data << "";
        temp = temp->next;
    }
}

int main()
{

    Node *head = NULL;

    insert_at_end(head, 12);
    insert_at_end(head, 16);
    insert_at_end(head, 71);
    insert_at_end(head, 81);
    insert_at_end(head, 91);

    printList(head);

    return 0;
}

It works fine if Head is not NULL ( If already have inserted value at start of list) but as you can see Head is NULL in start it gives a error , Probably the error is in insert_at_end function . I think i am missing some concept of pointers

drescherjm
  • 10,365
  • 5
  • 44
  • 64
  • 3
    One bug is that head is passed by value meaning a copy of `head` exists in the `insert_at_end` function. Any change it makes to head will not be seen in `int main()`. Change `void insert_at_end(Node *head, int data)` to `void insert_at_end(Node* & head, int data)` to fix that. I would answer but I am sure this has many duplicates. – drescherjm Dec 05 '21 at 15:06
  • See [Why should I not #include ?](https://stackoverflow.com/q/31816095) and [Why using namespace std is bad practice](https://stackoverflow.com/questions/1452721). – prapin Dec 05 '21 at 16:48
  • Thanks man .It Really Helped !! – Prince Kumar Dec 06 '21 at 13:17

1 Answers1

1

the problem with your code is that the function insert_at_end is taking a pointer to the head, meaning it can't modify the head pointer itself. You could make it this way though :

void insert_at_end(Node **head, int data)
{
    Node *temp = new Node();
    temp->data = data;
    temp->next = NULL;

    if (*head == NULL)
    {
        *head = temp;
    }
    else
    {
        Node *last = *head;
        while (last->next != NULL)
        {
            last = last->next;
        }
        last->next = temp;
        cout << "Inserted " << data << " at the End \n";
    }
}
  • Thanks for help but only problem was I had to use pointer everytime in insert_at_end() with this solution that's why I already avoided it But Thanks to @drescherjm , Now I have a great way to do this – Prince Kumar Dec 06 '21 at 13:21