【LeetCode】Linked List Cycle

【题目】

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

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

【分析】

检查链表内有没有闭环。其他人的思路,两个指针,一个每次跳一个 Node,另一个每次2个 Node,如果存在闭环,最终快指针会追上慢指针,两者相等。如果无闭环,快指针会先到 None。

【代码】

# Definition for singly-linked list.
# 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):
        slow = fast = head
        if head == None or head.next == None:
            return False
        else :
            while fast and fast.next :
                slow = slow.next
                fast = fast.next.next
                if fast == slow:
                    return True
            return False
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容