-
-
Notifications
You must be signed in to change notification settings - Fork 241
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
Comments
/**
* @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
}; |
哈希法/**
* 链表节点类
*/
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;
}; |
题目链接:https://leetcode.cn/problems/linked-list-cycle /**
* 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
No description provided.
The text was updated successfully, but these errors were encountered: