0
点赞
收藏
分享

微信扫一扫

【Leetcode 141】环形链表

环形链表题目

【Leetcode 141】环形链表_链表
【Leetcode 141】环形链表_结点_02
【Leetcode 141】环形链表_结点_03

public boolean hasCycle(ListNode head) {
Set<ListNode> nodesSeen = new HashSet<>();
while (head != null) {
if (nodesSeen.contains(head)) {
return true;
} else {
nodesSeen.add(head);
}
head = head.next;
}
return false;
}

【Leetcode 141】环形链表_.net_04
【Leetcode 141】环形链表_结点_05

public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
ListNode slow = head;
ListNode fast = head.next;
while (slow != fast) {
if (fast == null || fast.next == null) {
return false;
}
slow = slow.next;
fast = fast.next.next;
}
return true;
}

【Leetcode 141】环形链表_链表_06
参考链接
​​​ https://leetcode-cn.com/problems/linked-list-cycle/solution/huan-xing-lian-biao-by-leetcode/​​

扩展拿到环的入口结点
​​​ https://zhuanlan.zhihu.com/p/103626709​​


举报

相关推荐

0 条评论