leetcode141:

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

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

示例 1:

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

哈希表

=============================================Python=========================================

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        s = set()
        if not head:
            return False
        while head:
            if head not in s:
                s.add(head)
                head = head.next
            else:
                return True
        return False

=========================================Java=======================================

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
        HashSet<ListNode> s = new HashSet<>();
        if (head == null) {
            return false;
        }
        while (head != null) {
            if (s.contains(head) == false) {
                s.add(head);
                head = head.next;
            } else {
                return true;
            }
        }
        return false;
    }
}

=========================================Go==================================

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func hasCycle(head *ListNode) bool {
    m := make(map[*ListNode]int)
    for head != nil {
        if _, ok := m[head]; ok{
            return true
        }
        m[head] = 1
        head = head.Next
    }
    return false
}

双指针

=============================================Python=========================================

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        fast = slow = head
        if not head:
            return False
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
            if slow == fast:
                return True
        return False
原文地址:https://www.cnblogs.com/liushoudong/p/13496845.html