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