环形链表,有人通过了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

同学看你学习很认真,你学习算法的初衷是什么?面试还是业务提升?

0
2
快乐动起来呀
回复
nkliyc
对的,算法最重要的是思路,遇到一个问题能思考出用什么样的方案去解决,而不是背知识点
2019-06-27
共2条回复

JavaScript版 数据结构与算法

填补前端同学的算法短板,掌握面试中最常见的算法与数据结构

2467 学习 · 395 问题

查看课程