logo头像
Snippet 博客主题

【Leetcode 141】Linked List Cycle

难度: 简单(Easy)

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

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

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
l1 = head
l2 = head
while l2 is not None:
if l2.next == l1:
return True
elif l2.next is None:
return False
l2 = l2.next.next
l1 = l1.next
return False

评论系统未开启,无法评论!