题目来源https://leetcode-cn.com/problems/middle-of-the-linked-list
问题①:按这个思路“将链表输出到数组,数组的话可以按索引找“来写的
var middleNode = function(head) {
let result = [head];
for(let i = 0, apple = head; apple != null; i++, apple = apple.next){
result[i] = apple.val;
}
console.log(result);
console.log(result.length);
console.log (result.slice(Math.floor(result.length/2)));
return Array.from(result);
}
为什么console能正常显示但是return却不行?
问题②:用快慢双指针
var middleNode = function(head) {
slow = fast = head;
while(fast && fast.next != null){ //为什么去掉fast 就会报错???
// console.log(slow.val +" "+fast.val);
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
去掉fast会报错,但不懂为什么
测试用例:[1,2,3,4,5,6]
感谢大佬们在百忙中解答我的疑问!!