leetcode 判断链表是否有环

 

# 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:
        while head:
            try:
                if head.visit == True:
                    return True
            except:
                head.visit = True
            head = head.next
            
        return False
# 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:
        one = ListNode(-10086)
        while head:
            if head.val == -10086:
                return True
            p = head.next
            head.next = one
            head = p
        return False

 

你可能感兴趣的:(leetcode)