# Insert a node at the end of a Singly Linked List Using C++

We have already learned about how to insert the element at the beginning of the linked list in C++. Now it’s time to explain how to insert an element at the end of a list. We have discussed more in the previous post. In this tutorial, we are going to see only the logic behind the insertion at the end.

Let’s look at the code:

#include <iostream> using namespace std; struct node { int data; node *next; }*head=NULL; void insert(int value) //creating the linked list { node *newnode; newnode=new node; newnode->data=value; newnode->next=NULL; if(head==NULL) { head=newnode; } else { node *tmp=head; while(tmp->next != NULL) tmp=tmp->next; tmp->next=newnode; } } void insert_last(int value) { node *newnode; newnode = new node; newnode->data=value; newnode->next=NULL; if(head==NULL) { head=newnode; } else { node *temp=head; while(temp->next!=NULL) { temp=temp->next; } temp->next=newnode; } } void print(node *t) { cout<<"Traversing from very first:-"; node *temp=t; while(temp->next != NULL) { cout<<temp->data<<" "; temp=temp->next; } cout<<temp->data<<" "; } int main() { int value,loc,position,n,i=0; cout<<"Enter the n value:"; cin>>n; cout<<"Enter the elements you want to insert:- "; do { cin>>value; insert(value); i=i+1; }while(i<n); print(head); cout<<endl<<"Insert at last:"; cin>>value; insert_last(value); print(head); return 0; }

In the above program only one thing we have to explain in the insert at the end function. The rest of the code, I have explained in the previous tutorial( to take references or to better understand this program, I would like to suggest to read: Insert at the beginning of a singly linked list).

So here we go to understand the insertion at the end of the list:

void insert_last(int value) { node *newnode; newnode = new node; newnode->data=value; newnode->next=NULL; if(head==NULL) { head=newnode; } else { node *temp=head; while(temp->next!=NULL) { temp=temp->next; } temp->next=newnode; }

In the above code snippet, we are just explaining the function insert_last. Here we can see:

- We are creating a new node which will contain the latest value to be inserted at the end of the array. The name of the new node here is newnode.
- Next of it, we are checking whether head==null or not! If so then that’s will be last and first
- If there is already an element there in the list then we are going to traverse the list to the end and then we are making a connection to that newnode. Like:

1. Checking whether temp->next!=NULL or not.

2. If this condition satisfies that’s means we are at the end of the array.

3. Now, we are linking the last element pointer to the newnode.

4. If we are at not at the end of the array then we will just move the temp to the next.

how can free this node in the memory?

thanks for watching