Insert At End of Linked List In JavaScript

In previous post, we learnt how to insert a mode at beginning of linked list in js, now in this post, we will learn how to insert node at end of linked list in javascript.

Insert At End of Linked List In JavaScript

class Node
{
    constructor(val)
     {
            this.data = val;
            this.next = null;
      }
}
var head = null;
function insertlast(val)
{
    var last = new Node(val);

    if(head == null)
        head = last;
    else
    {
        var lastNode = head;

        while(lastNode.next != null)
        {
            lastNode = lastNode.next;
        }

        lastNode.next = last;
    }
}
function print()
{
    var temp = head;
    while(temp != null)
    {
        document.write(temp.data);
        temp = temp.next;
    }
}
insertlast(5);
insertlast(10);
insertlast(15);
insertlast(20);

print();

In this program, we are doing following things:

  1. Creating a class Node and initialize the node object with constructor.
  2. Then we are initializing the data with given value and next as null.
  3. Initialize the head as NULL.
  4. Creating two functions, print and insertlast to look code neat and consize.
  5. In insertlast we are using variable last as new node
  6. Assigning the value and then checking if head is empty then make last as head.
  7. Else check by traversing whether the next node points to null or not.
  8. When the next node points to null make its next point to last and last next point to null.

The Output will be:

5
10
15
20

Shares
facebook sharing button Share
twitter sharing button Tweet
whatsapp sharing button Share
telegram sharing button Share
pinterest sharing button Pin

Leave a Comment