Javascript Program For Writing A Function To Delete A Linked List
Last Updated :
09 Sep, 2024
Improve
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 program to delete
// a linked list
// Head of the list
let 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 */
let 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);
console.log("Deleting the list");
deleteList();
console.log("Linked list deleted");
// This code contributed by Rajput-Ji
Output
Deleting the list Linked list deleted
Complexity Analysis:
- Time Complexity: O(n)
- Auxiliary Space: O(1)
Please refer complete article on Write a function to delete a Linked List for more details!