题目链接

141. 环形链表

题目描述

给定一个链表,判断链表中是否有环。

如果链表中存在环,则返回 true 。 否则,返回 false

解题思路

1. 哈希表

将链表节点不断添加到哈希表中,在添加过程中如果某个节点已经存在于哈希表中,说明链表有环,因为同一个对象地址相同。

  1. public class Solution {
  2. public boolean hasCycle(ListNode head) {
  3. HashSet<ListNode> set = new HashSet<>();
  4. while (head != null) {
  5. if (set.contains(head)) {
  6. return true;
  7. }
  8. set.add(head);
  9. head = head.next;
  10. }
  11. return false;
  12. }
  13. }

复杂度分析

  • 时间复杂度LeetCode141. 环形链表 - 图1,N 取决于链表的节点个数。
  • 空间复杂度LeetCode141. 环形链表 - 图2,哈希表需要的额外空间。

    2. 双指针

设置 fast 指针每次前进两步,slow 指针每次前进一步,如果链表有环,两指针一定会相遇。

  1. public class Solution {
  2. public boolean hasCycle(ListNode head) {
  3. ListNode fast = head;
  4. ListNode slow = head;
  5. while (fast != null && fast.next != null) {
  6. fast = fast.next.next;
  7. slow = slow.next;
  8. if (fast == slow) {
  9. return true;
  10. }
  11. }
  12. return false;
  13. }
  14. }

复杂度分析

  • 时间复杂度LeetCode141. 环形链表 - 图3,N 取决于链表节点个数。
  • 空间复杂度LeetCode141. 环形链表 - 图4