# Javascript Program For Inserting A Node In A Linked List

• Last Updated : 27 Dec, 2021

We have introduced Linked Lists in the previous post. We also created a simple linked list with 3 nodes and discussed linked list traversal.
All programs discussed in this post consider the following representations of the linked list.

## Javascript

 ``

In this post, methods to insert a new node in linked list are discussed. A node can be added in three ways
1) At the front of the linked list
2) After a given node.
3) At the end of the linked list.

Add a node at the front: (4 steps process) Following are the 4 steps to add a node at the front.

## Javascript

 ``

Time complexity of push() is O(1) as it does a constant amount of work.
Add a node after a given node: (5 steps process)
We are given a pointer to a node, and the new node is inserted after the given node.

## Javascript

 ``

Time complexity of insertAfter() is O(1) as it does a constant amount of work.

Add a node at the end: (6 steps process)
The new node is always added after the last node of the given Linked List. For example if the given Linked List is 5->10->15->20->25 and we add an item 30 at the end, then the Linked List becomes 5->10->15->20->25->30.
Since a Linked List is typically represented by the head of it, we have to traverse the list till the end and then change the next to last node to a new node. Following are the 6 steps to add node at the end.

## Javascript

 ``

Time complexity of append is O(n) where n is the number of nodes in the linked list. Since there is a loop from head to end, the function does O(n) work.
This method can also be optimized to work in O(1) by keeping an extra pointer to the tail of the linked list/

Following is a complete program that uses all of the above methods to create a linked list.

## Javascript

 ``

Output:

` Created Linked list is:  1  7  8  6  4`

Please refer complete article on Linked List | Set 2 (Inserting a node) for more details!

My Personal Notes arrow_drop_up