JavaScript:如何查詢連結串列的中間元素?
對於給定的連結串列,編寫一個JavaScript程式來查詢其中間元素。在這裡,連結串列是一種線性資料結構。
如果連結串列中元素個數為偶數,則會有兩個中間節點。在這種情況下,中間元素將是這兩個元素中的後一個元素。
示例場景
Input: linked_list = 1->2->3->4->5->6-> null Output: middle_element = 4
使用迭代
遍歷整個列表並計算節點數。現在,遍歷節點直到count/2,並返回count/2,即中間元素。
示例
下面的JavaScript程式演示瞭如何查詢連結串列的中間元素。
<html>
<head>
<title>Middle Element of Linked List</title>
</head>
<body>
<script>
class Node {
constructor(val) {
this.data = val;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
}
// to add a new node
push(new_data) {
let new_node = new Node(new_data);
if (!this.head) {
this.head = new_node;
} else {
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = new_node;
}
}
// counting nodes
getCount() {
let count = 0;
let current = this.head;
while (current) {
count++;
current = current.next;
}
return count;
}
// for getting middle node
printMiddle() {
let count = this.getCount();
let mid = Math.floor(count / 2);
let current = this.head;
for (let i = 0; i < mid; i++) {
current = current.next;
}
return current.data;
}
}
const linkedlist = new LinkedList();
linkedlist.push('Node 12');
linkedlist.push('Node 24');
linkedlist.push('Node 48');
linkedlist.push('Node 95');
linkedlist.push('Node 56');
document.write('The middle element is: ' + linkedlist.printMiddle());
</script>
</body>
</html>
執行此程式碼後,將產生以下輸出:
The middle element is: Node 48
使用雙指標
使用兩個指標(慢指標和快指標)遍歷連結串列。慢指標一次移動一個節點,快指標一次移動兩個節點,直到快指標指向null。當快指標到達末尾時,慢指標將指向中間元素。
示例
在下面的示例中,我們將使用雙指標方法在JavaScript中查詢連結串列的中間元素。
<html>
<head>
<title>Middle Element of Linked List</title>
</head>
<body>
<script>
// Defining the head pointer
var head;
/* Linked list node */
class Node {
constructor(val) {
this.data = val;
this.next = null;
}
}
/* Function to print middle
of linked list */
function printMiddle(){
var slow_ptr = head;
var fast_ptr = head;
if (head != null){
while (fast_ptr != null &&
fast_ptr.next != null){
fast_ptr = fast_ptr.next.next;
slow_ptr = slow_ptr.next;
}
document.write(
"The middle element is [" + slow_ptr.data + "] <br/><br/>"
);
}
}
/* 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;
}
/*
* This function prints contents of linked
list starting from the given node
*/
function printList() {
var tnode = head;
while (tnode != null) {
document.write(tnode.data + "->");
tnode = tnode.next;
}
document.write("NULL<br/>");
}
for (i = 4; i > 0; --i) {
push(i);
printList();
printMiddle();
}
</script>
</body>
</html>
它將產生以下輸出:
5->NULL The middle element is [5] 4->5->NULL The middle element is [5] 3->4->5->NULL The middle element is [4] 2->3->4->5->NULL The middle element is [4]
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP