Open In App

Javascript Program For Writing A Function To Delete A Linked List

Improve
Improve
Like Article
Like
Save
Share
Report

A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers. This article focuses on writing a function to delete a linked list.

Implementation: 

Javascript




<script>
// Javascript program to delete
// a linked list
 
// Head of the list
var head;
 
// Linked List node
class Node
{
    constructor(val)
    {
        this.data = val;
        this.next = null;
    }
}
 
// Function deletes the entire
// linked list
function deleteList()
{
    head = null;
}
 
// Inserts a new Node at front
// of the list.
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;
}
 
// Use push() to construct list
// 1->12->1->4->1
push(1);
push(4);
push(1);
push(12);
push(1);
 
document.write("Deleting the list<br/>");
deleteList();
document.write("Linked list deleted");
// This code contributed by Rajput-Ji
</script>


Output:

Deleting linked list
Linked list deleted

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

Please refer complete article on Write a function to delete a Linked List for more details!
 


Last Updated : 09 Dec, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads