Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

给定一个链表,判断是否有环存在。Follow up: 不使用额外空间。

解法:双指针,一个慢指针每次走1步,一个快指针每次走2步的,如果有环的话,两个指针肯定会相遇。

Java:

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

Python:

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    # @param head, a ListNode
    # @return a boolean
    def hasCycle(self, head):
        fast, slow = head, head
        while fast and fast.next:
            fast, slow = fast.next.next, slow.next
            if fast is slow:
                return True
        return False  

C++:

class Solution {
public:
    bool hasCycle(ListNode *head) {
        ListNode *slow = head, *fast = head;
        while (fast && fast->next) {
            slow = slow->next;
            fast = fast->next->next;
            if (slow == fast) return true;
        }
        return false;
    }
};

  

类似题目:

[LeetCode] 142. Linked List Cycle II 链表中的环 II

 

 

相关文章:

  • 2021-11-09
  • 2021-07-08
  • 2022-02-02
  • 2022-01-05
  • 2021-10-04
  • 2022-01-09
  • 2021-04-23
  • 2021-08-08
猜你喜欢
  • 2022-12-23
  • 2020-04-13
  • 2021-06-18
  • 2022-12-23
  • 2022-12-23
  • 2022-01-10
  • 2021-10-01
相关资源
相似解决方案