来源

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/linked-list-cycle/

描述

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

为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从0开始)。如果 pos 是 -1,则在该链表中没有环。

示例 1:
输入:head = [3,2,0,-4], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。

示例 2:
输入:head = [1], pos = -1
输出:false
解释:链表中没有环。

题解

双指针法

  1. /**
  2. * Definition for singly-linked list.
  3. * class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) {
  7. * val = x;
  8. * next = null;
  9. * }
  10. * }
  11. */
  12. public class Solution {
  13. public boolean hasCycle(ListNode head) {
  14. if (head == null || head.next == null) return false;
  15. ListNode slow = head;
  16. ListNode fast = head.next;
  17. while (slow != fast) {
  18. if (fast == null || fast.next == null) {
  19. return false;
  20. }
  21. slow = slow.next;
  22. fast = fast.next.next;
  23. }
  24. return true;
  25. }
  26. }

复杂度分析
• 时间复杂度:141. 环形链表(Linked List Cycle) - 图1
• 空间复杂度:141. 环形链表(Linked List Cycle) - 图2