struct Node
{
int data;
struct Node *next;
};
//insert a new node in an empty list
struct Node *insertInEmpty(struct Node *last, int new_data)
{
// if last is not null then list is not empty, so return
if (last != nullptr)
return last;
// allocate memory for node
struct Node *temp = new Node;
// Assign the data.
temp -> data = new_data;
last = temp;
// Create the link.
last->next = last;
return last;
}
//insert new node at the beginning of the list
struct Node *insertAtBegin(struct Node *last, int new_data)
{
//if list is empty then add the node by calling insertInEmpty
if (last == nullptr)
return insertInEmpty(last, new_data);
//else create a new node
struct Node *temp = new Node;
//set new data to node
temp -> data = new_data;
temp -> next = last -> next;
last -> next = temp;
return last;
}