leetcode: 141. Linked List Cycle

Difficulty

Easy.

Problem

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

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

AC

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

class Solution():
    def hasCycle(self, head):
        if not head or not head.next:
            return False
        slow = fast = head
        while fast.next and fast.next.next:
            slow, fast = slow.next, fast.next.next
            if fast == slow:
                return True
        return False

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券