Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การหาโหนดกลางของลิงก์ลิสต์ใน JavaScript

ปัญหา

เราต้องเขียนฟังก์ชัน JavaScript ที่รับหัว (head) ของลิงก์ลิสต์เป็นอาร์กิวเมนต์เดียว

ฟังก์ชันควรคืนค่าที่เก็บอยู่ในโหนดกลางของลิสต์ และหากมีโหนดกลางสองโหนด เราควรคืนค่าตัวที่สองของพวกมัน

ตัวอย่างเช่น หากลิสต์เป็นแบบนี้:

อินพุต

[4, 6, 8, 9, 1]

เอาต์พุต

const output = 8;

ตัวอย่างโค้ด

class Node {
constructor(data) {
this.data = data;
this.next = null;
};
};
class LinkedList {
constructor() {
this.head = null;
this.size = 0;
};
};
LinkedList.prototype.add = function(data) {
const newNode = new Node(data);
let curr;
if (this.head === null) {
this.head = newNode;
} else {
curr = this.head;
while (curr.next) {
curr = curr.next;
}
curr.next = newNode;
};
this.size++;
};
const list = new LinkedList();
list.add(4);
list.add(6);
list.add(8);
list.add(9);
list.add(1);
const findMiddle = (head) => {
let slow = head;
let fast = head;
while (fast && fast.next) {
slow = slow.next;
fast = fast.next.next;
}
return slow.data;
};
console.log(findMiddle(list.head));

ผลลัพธ์

8