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 listvar 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->1push(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!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
