JavaScript 連結串列中搜索元素的程式
連結串列是一種線性資料結構,其中每個元素(也稱為節點)包含一個數據值和指向列表中下一個節點的引用。連結串列上一個常見的操作是搜尋特定元素。這涉及遍歷列表並將每個節點的資料值與目標元素進行比較,直到找到匹配項。
以下是一個我們將在這整篇文章中使用的連結串列示例:
10 -> 20 -> 30 -> 40 -> null
在此連結串列中,每個節點都包含一個值,箭頭指示序列中的下一個節點。列表以頭節點開始,頭節點包含值 10,並以尾節點結束,尾節點包含值 40 並指向 null。我們將使用此連結串列來演示如何使用 JavaScript 在連結串列中搜索元素。
讓我們看看下面的例子:
Linked list: 10 -> 20 -> 30 -> 40 -> null Input: 40 Output: Element found at index 3 Input: 10 Output: Element found at index 0 Input: null Output: Element not found
現在讓我們討論在 JavaScript 中建立連結串列的演算法。
演算法
步驟 1 - 定義一個具有兩個屬性的 Node 類:value 和 next。value 屬性表示儲存在節點中的資料,next 屬性是指向連結串列中下一個節點的引用。
步驟 2 - 定義一個具有三個屬性的 LinkedList 類:head、tail 和 length。head 屬性表示連結串列中的第一個節點,tail 屬性表示連結串列中的最後一個節點,length 屬性表示連結串列中節點的數量。
步驟 3 - 在 LinkedList 類中定義一個名為 add 的方法,該方法將一個值作為引數。add 方法應該建立一個具有給定值的新節點並將其新增到連結串列的末尾。
步驟 4 - 在 LinkedList 類中定義一個名為 remove 的方法,該方法將一個值作為引數。remove 方法應該刪除連結串列中第一個具有給定值的節點。
步驟 5 - 在 LinkedList 類中定義一個名為 search 的方法,該方法將一個值作為引數。search 方法應該返回連結串列中第一個具有給定值的節點,如果未找到節點則返回 null。
步驟 6 - 在 LinkedList 類中定義一個名為 reverse 的方法,該方法反轉連結串列中節點的順序。
示例:使用 JavaScript 實現上述演算法
以下程式定義了一個 Node 類和一個 LinkedList 類。Node 類使用給定的資料值和指向列表中下一個節點的引用建立一個新節點。LinkedList 類使用一個最初指向 null 的頭節點和一個設定為 0 的 size 屬性建立一個新的連結串列。add 方法將一個新節點新增到連結串列的末尾。search 方法遍歷連結串列,如果找到元素則返回該元素的索引,或者返回一條訊息,指示未找到該元素。最後,程式建立一個新的連結串列,向其中新增元素,並搜尋特定元素。
// Define the Node class for a singly linked list
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
// Define the LinkedList class
class LinkedList {
constructor() {
this.head = null;
this.size = 0;
}
// Add an element to the linked list
add(element) {
const node = new Node(element);
// If the linked list is empty, set the new node as the head
if (this.head === null) {
this.head = node;
} else {
// Traverse to the end of the linked list and add the new node
let current = this.head;
while (current.next !== null) {
current = current.next;
}
current.next = node;
}
this.size++;
}
// Search for an element in the linked list
search(element) {
let current = this.head;
let index = 0;
// Traverse through the linked list until the element is found
while (current !== null) {
if (current.data === element) {
return `Element found at index ${index}`;
}
current = current.next;
index++;
}
return "Element not found";
}
}
// Create a new linked list
const ll = new LinkedList();
// Add elements to the linked list
ll.add(10);
ll.add(20);
ll.add(30);
ll.add(40);
ll.add(50);
// Search for an element in the linked list
const result = ll.search(30);
console.log(result);
結論
使用 JavaScript 在連結串列中搜索元素的程式涉及建立 'LinkedList' 類,該類定義了向列表中新增元素和在列表中搜索元素的方法。該程式使用 while 迴圈遍歷連結串列,並將每個節點中的資料元素與要搜尋的元素進行比較。如果找到該元素,則程式返回該節點的索引,如果未找到該元素,則程式返回“未找到元素”。
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP