ปัญหา
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับหน้าที่ในส่วนหัวของรายการที่เชื่อมโยงเป็นอาร์กิวเมนต์แรกและอาร์กิวเมนต์เดียว
ฟังก์ชันของเราควรคืนค่าที่เก็บไว้ในโหนดกลางสุดของรายการ และหากมีโหนดตรงกลางสุดสองโหนด เราควรส่งคืนโหนดที่สองของโหนดเหล่านั้น
ตัวอย่างเช่น หากรายการเป็นดังนี้:
ป้อนข้อมูล
[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