LeetCode--141. Linked List Cycle(检测链表是否有环)

题目:
给定一个链表,检测该链表是否有环。有环返回True,否则返回False。

解题思路:
建立一个快指针和一个慢指针,快指针移动速度为慢指针的两倍,若两个指针能碰上,则说明链表有环,否则链表无环。

代码:

# 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
        """
        if head==None:
            return False
        head_1 = head
        head_2 = head.next
        while(head_2):
            if head_2.val == head_1.val:
                return True
            try:
                head_2 = head_2.next.next
            except:
                return False
            head_1 = head_1.next
        return False

猜你喜欢

转载自blog.csdn.net/xiaoxiaoley/article/details/79895620
今日推荐