在 JavaScript 中查找链表的最中间节点
问题
我们需要编写一个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
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下