Javascript Data Structure Tutorial - Javascript Linked List








A linked list is a collection of objects called nodes.

Each node is linked to a successor node in the list using an object reference.

The reference to another node is called a link.

To insert a new node, the link of the node before the inserted node is changed to point to the new node, and the new node's link is set to the node the previous node was pointing to.

To remove an item from a linked list, the link of the node before the removed node is redirected to point to the node the removed node is pointing to, while also pointing the removed node to null.





Node class

We'll create a Node class to represent nodes in a linked list.

The Node class consists of two properties: element, which store's the node's data, and next, which stores a link to the next node in the linked list.

function Node(element) { 
    this.element = element; 
    this.next = null; 
} 

LinkedList class

The LinkedList class provides functions for inserting nodes, removing nodes, displaying a list, and other functions.

The only property stored in a linked list is a node to represent the head of the list.


function Node(element) { //  www.ja  v a  2 s .com
    this.element = element; 
    this.next = null; 
} 

function LinkedList() { 
    this.head = new Node("head"); 
    this.find = find; 
    this.insert = insert; 
    this.remove = remove; 
    this.display = display; 
    this.findPrevious = findPrevious; 
    this.remove = remove; 
} 

function find(item) { 
    var currNode = this.head; 
    while (currNode.element != item) { 
        currNode = currNode.next; 
    } 
    return currNode; 
} 
function insert(newElement, item) { 
    var newNode = new Node(newElement); 
    var current = this.find(item); 
    newNode.next = current.next; 
    current.next = newNode; 
} 
function display() { 
    var currNode = this.head; 
    while (!(currNode.next == null)) { 
        console.log(currNode.next.element); 
        currNode = currNode.next; 
    } 
} 


//Removing Nodes from a Linked List 

function findPrevious(item) { 
    var currNode = this.head; 
    while (!(currNode.next == null) && (currNode.next.element != item)) { 
        currNode = currNode.next; 
    } 
    return currNode; 
} 
function remove(item) { 
    var prevNode = this.findPrevious(item); 
    if (!(prevNode.next == null)) { 
        prevNode.next = prevNode.next.next; 
    } 
} 

var cities = new LinkedList(); 
cities.insert("A", "head"); 
cities.insert("B", "A"); 
cities.insert("C", "B"); 
cities.display();
cities.remove("C"); 
cities.display();

The code above generates the following result.