Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

环形链表 #287

Open
Sunny-117 opened this issue Nov 8, 2022 · 3 comments
Open

环形链表 #287

Sunny-117 opened this issue Nov 8, 2022 · 3 comments

Comments

@Sunny-117
Copy link
Owner

No description provided.

@lxy-Jason
Copy link
Contributor

/**
 * @param {ListNode} head
 * @return {boolean}
 */
var hasCycle = function(head) {
    let cur = head;
    while(cur){
        if(cur.dirty){ //加个标记,如果有环,这个标记就知道已经遍历过了
            return true
        }
        cur.dirty = true
        cur = cur.next;
    }
    return false
};

@xiaodye
Copy link

xiaodye commented Jan 11, 2023

哈希法

/**
 * 链表节点类
 */
class ListNode {
  val: number;
  next: ListNode | null;
  constructor(val: number, next: ListNode | null = null) {
    this.val = val;
    this.next = next;
  }
}

/**
 * 给定一个链表,判断链表中是否有环。
 * @param head
 * @returns
 */
const detectCycle = function (head: ListNode | null): boolean {
  const visted = new Set<ListNode>();

  while (head) {
    if (visted.has(head)) return true;
    visted.add(head);
    head = head.next;
  }
  return false;
};

@Pcjmy
Copy link
Contributor

Pcjmy commented Feb 27, 2023

题目链接:https://leetcode.cn/problems/linked-list-cycle
时间复杂度:O(n)
解题思路:将访问过的结点打上标记,访问到有标记的点说明有环,否则说明无环

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */

/**
 * @param {ListNode} head
 * @return {boolean}
 */
var hasCycle = function(head) {
    while(head)
    {
        if(head.tag) return true;
        head.tag=true;
        head=head.next;
    }
    return false;
};

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants