How to Delete a Linked List in JavaScript?

JavascriptWeb DevelopmentFront End Technology

In this article, we are going to explore Linked List and how to delete a linked list in JavaScript.

A Linked List is a data structure that is used for storing raw data. The Linked List elements are not stored in contiguous memory locations. The elements in a Linked List are linked using pointers.

Example

In the below example, we are going to delete the linked list in JavaScript.

# index.html

<html>
<head>
   <title>Computed Property</title>
</head>
<body>
   <h1 style="color: red;">
      Welcome To Tutorials Point
   </h1>
   <script>
      // Javascript program to delete
      // a linked list
      // Declaring the HEAD
      var head;
      class Node
      {
         constructor(val)
         {
            this.data = val;
            this.next = null;
         }
      }
      // Deleting the entire linked list
      function deleteList()
      {
         head = null;
      }
      // Inserting a new node.
      function push(new_data)
      {
         /* 1 & 2: Allocate the Node &
         Put in the data */
         var new_node = new Node(new_data);
         // 3. Make next of new Node as head
         new_node.next = head;
         // 4. Move the head to point to new Node
         head = new_node;
      }
      function display() {
         if(head==null) {
            document.write("null");
         }
         while(head!=null) {
            document.write("<br\>" + head.data);
            head = head.next;
         }
      }
      // Use push() to construct list
      // 1->12->1->4->1
      push(1);
      push(4);
      push(1);
      push(12);
      push(1);
      document.write("<h3>Elements in List Before Deletion: </h3>");
      display();
      document.write("<br\><h4>Deleting the list</h4>");
      deleteList();
      document.write("<br\><h3>Elements in List After Deletion: </h3>");
      display();
   </script>
</body>
</html>

Output

It will produce the following output.

raja
Updated on 28-Apr-2022 12:18:55

Advertisements