如何在 JavaScript 中删除链表?
在本文中,我们将探讨链表以及如何在 JavaScript 中删除链表。
链表是一种用于存储原始数据的数据结构。链表元素不存储在连续的内存位置中。链表中的元素使用指针链接。
示例
在下面的示例中,我们将删除 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>
输出
它将产生以下输出。
广告