# Insert a node in Linked List before a given node

Given a node of Linked List N and a value K, the task is to insert the node with value K in the linked list before the given node N.

Structure of the Node:

## C++

 // Structure of Node struct Node {     int data;     Node* next;       // Constructor of Node     Node(int val, Node* link = 0)         : data(val), next(link)     {     } };

## Java

 // Structure of Node public class Node {     public int data;     public Node next;         // Constructor of Node     public Node(int val, Node link = null)     {         this.data = val;         this.next = link;     } }   // This code is contributed by divyesh072019

## Python3

 # Structure of Node class Node:           # Constructor of Node     def __init__(self, val, link = None):                   self.data = val         self.next = link           # This code is contributed by pratham76

## C#

 // Structure of Node public class Node {     public int data;     public Node next;         // Constructor of Node     public Node(int val, Node link = null)     {         this.data = val;         this.next = link;     } };   // This code is contributed by rutvik_56

## Javascript



Output:

5 8 6

In the given problem there might be two cases:

• Given node is the head node.
• Given node is any valid node except the head.

### When given Node is the Head Node:

The idea is to create a new node with the given value K. Then the next part of the new node will be updated with the pointer head. And finally, the head will be updated with the new node’s address. Below is the image of the same:

### When given Node is any valid node except head node:

The simplest approach is to traverse the given linked list to search the previous node of the given node. Then, create the new node with the given value K.Now, update the next part of the new node with the address of the given node and the next part of the previous node with the address of the new node. Below is an illustration of the approach with the help of image:

Below is the implementation of the above approach:

## Javascript



Output:

5 8 6

Time Complexity: O(N)
Auxiliary Space: O(1)

Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Previous
Next