likes
comments
collection
share

算法(TS):环形链表

作者站长头像
站长
· 阅读数 2

给你一个链表的头节点 head ,判断链表中是否有环。如果链表中存在环 ,则返回 true 。 否则,返回 false 。

如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。

提示:

  • 链表中节点的数目范围是 [0, 104]
  • -105 <= Node.val <= 105
  • pos 为 -1 或者链表中的一个 有效索引

进阶: 你能用 O(1)(即,常量)内存解决此问题吗?

算法(TS):环形链表

上述链表有环

解法一

遍历链表,用一个 Set 对象保持链表中的节点,如果在遍历的时候发现 Set 对象中已经存在某个节点,则说明该链表有环

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function hasCycle(head: ListNode | null): boolean {
    const NodeSet = new WeakSet<ListNode>()

    while(head) {
        if(NodeSet.has(head)) {
            return true
        }

        NodeSet.add(head)
        head = head.next
    }

    return false
};

算法(TS):环形链表

时间复杂度O(n),空间负责度O(n)

解答二

通过快慢指针。为什么快慢指针能解决这个问题?就好比两个速度不同的人在操场上跑圈,速度快的人在 n 圈之后又能与速度慢的人相遇。

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function hasCycle(head: ListNode | null): boolean {
    let fast = head
    let low = head
    while(fast && fast.next) {
        low = low.next
        fast = fast.next.next

        if(low === fast) {
            return true
        }
    }
    return false
};

算法(TS):环形链表

时间复杂度O(n),空间负责度O(1)