0

I wrote this piece of code in C++ for the function Insert At Tail in a linked list but when the list is empty it is not inserting the data.

This is the picture of it:- https://i.stack.imgur.com/wKkXk.png

I don't know why the lines from 35 to 39 are not executed.

This is my code:-

#include <iostream>
using namespace std;

class node
{
public:
    int data;
    node *next;

    // Constructor
    node(int d)
    {
        data = d;
        next = NULL;
    }
};

void display(node *head)
{
    if (head == NULL)
    {
        cout << "The list is empty !!" << endl;
    }

    while (head != NULL)
    {
        cout << head->data << "->";
        head = head->next;
    }
    cout << endl;
}

void Insert_At_Tail(node *head, int data)
{
    if (head == NULL)
    {
        head = new node(data);
        return;
    }

    node *tail = head;
    while (tail->next != NULL)
    {
        tail = tail->next;
    }
    tail->next = new node(data);
    return;
}

int main()
{
    node *head = NULL;
    int data;
    cout << "Enter the data: ";
    cin >> data;
    Insert_At_Tail(head, data);
    display(head);
    return 0;
}

This is the snapshot of my output: https://i.stack.imgur.com/FFGj6.png

2 Answers2

1

The problem is that you don't change head at the caller. Either take a reference to the head

void insert_at_tail(node*& head, int data)

or better, return the new head:

void insert_at_tail(node *head, int data) {
    if (!head) return new node(data);
    node *tail = head;
    while (tail->next != NULL) tail = tail->next;
    tail->next = new node(data);
    return head;
}

called like such:

head = insert_at_tail(head, data);

Even better is to wrap the whole thing into a class so you can write linked_list.insert_at_tail(data) and only have to mutate its members.

orlp
  • 98,226
  • 29
  • 187
  • 285
1
void Insert_At_Tail(node *head, int data)

In C++, by default function parametes are passed by value. This head parameter is a copy of the parameter that the caller passes in.

   head = new node(data);

This sets the new head pointer. This is fine, but because this head is a copy of the original parameter, this does absolutely nothing, whatsoever, to the caller's passed-in head pointer. All this does is set the function's head parameter/variable. This has no effect on the head that was passed into this function.

You can do one of two things (your choice):

  1. Pass the parameter by reference

  2. return the new value of the head pointer from this function (which could be unchanged from what was passed in, if there were no changes to the head pointer), and have the caller make save the new head pointer.

Sam Varshavchik
  • 84,126
  • 5
  • 57
  • 106