Add elements to a linked list using Javascript

In JavaScript, adding elements to a linked list requires careful pointer manipulation to maintain the list structure. We need to create a function insert(data, position) that inserts data at the specified position.

Implementation Steps

  • Create a new Node with the provided data
  • Check if the list is empty. If so, add the node as head and return
  • Iterate to the desired position using a current element pointer
  • Update the new node's next pointer to point to the current node's next
  • Update the current node's next pointer to point to the new node

Visual Representation

10 20 30 15 Head New Node Insert at position 2

Insert Method Implementation

class Node {
    constructor(data) {
        this.data = data;
        this.next = null;
    }
}

class LinkedList {
    constructor() {
        this.head = null;
        this.length = 0;
    }
    
    insert(data, position = this.length) {
        let node = new Node(data);
        
        // If list is empty, make new node the head
        if (this.head === null) {
            this.head = node;
            this.length++;
            return this.head;
        }
        
        // If inserting at position 0 (beginning)
        if (position === 0) {
            node.next = this.head;
            this.head = node;
            this.length++;
            return node;
        }
        
        let iter = 1;
        let currNode = this.head;
        
        // Traverse to the position before insertion point
        while (currNode.next != null && iter  ";
            current = current.next;
        }
        console.log(result);
    }
}

Example Usage

let list = new LinkedList();
list.insert(10);
list.insert(20);
list.insert(30);
list.insert(15, 2); // Insert 15 at position 2
list.display();
10 -> 30 -> 15 -> 20 -> 

Key Points

  • The position parameter defaults to the end of the list if not specified
  • Position 0 inserts at the beginning (new head)
  • Always update the new node's next pointer before updating the previous node's next
  • Handle edge cases like empty lists and insertion at the beginning

Conclusion

Inserting elements into a linked list requires careful pointer manipulation to maintain list integrity. The key is to properly link the new node between existing nodes while preserving the chain structure.

Updated on: 2026-03-15T23:18:59+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements