Inserting at the end involves traversing the entire list until we reach the last node. We then set the last node's next reference to point to the new node, making the new node the last element in the list.
Following is the approach to add a new node at the end of the linked list:
Create a new node and set its next pointer as NULL since it will be the last node.
Store the head reference in a temporary variable
If the Linked List is empty, make the new node as the head and return
Else traverse till the last node
Change the next pointer of the last node to point to the new node
Below is the implementation of the approach:
Output
1 -> 2 -> 3 -> 4 -> 5 -> 6
Time Complexity: O(n) where nis the length of the linked list Auxiliary Space: O(1)