环形链表,有人通过了leetcode测试吗,如何改写代码才能通过
来源:9-4 环形链表-代码实操

nkliyc
2019-06-25
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {boolean}
*/
// var hasCycle = function(head) {
// let slow = head
// // 快指针
// let fast = head.next
// while (1) {
// if (!fast || !fast.next) {
// return false
// } else if( fast === slow || fast.next === slow) {
// return true
// } else {
// slow = slow.next
// fast = fast.next.next
// }
// }
// };
// 声明链表节点
class Node {
constructor (value) {
this.val = value
this.next = undefined
}
}
// 声明链表数据结构
class NodeList {
constructor (arr) {
// 声明链表的头部节点
let head = new Node(arr.shift())
let next = head
arr.forEach(item => {
next.next = new Node(item)
next = next.next
})
return head
}
}
function hasCycle(head, pos) {
head = new NodeList(head)
if(pos !== -1) {
let tmp = head
for (let i = 0; i < pos; i++) {
tmp = tmp.next
}
let posNode = tmp
let next = head
while (1) {
if (!next.next) {
next.next = posNode
break
}
next = next.next
}
}
// 慢指针
let slow = head
// 快指针
let fast = head.next
while (1) {
if (!fast || !fast.next) {
return false
} else if( fast === slow || fast.next === slow) {
return true
} else {
slow = slow.next
fast = fast.next.next
}
}
}
写回答
1回答
-
快乐动起来呀
2019-06-25
同学看你学习很认真,你学习算法的初衷是什么?面试还是业务提升?
022019-06-27
相似问题
计数二进制字串的match中的正则无效
回答 2
在力扣上测试通过了提交的时候出错
回答 1
这样修改就能在LeetCode通过了
回答 2
改了个LeetCode通过的,但效率好低
回答 1
老师,直接修改原数组的做法如何呢
回答 2