LeetCode刷题_141.Linked List Cycle

原题链接:https://leetcode.com/problems/linked-list-cycle/description/
Given a linked list, determine if it has a cycle in it.

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

# 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
        """
        cur = head
        flag = False
        while cur:
            if cur.val != None:
                cur.val = None
                cur = cur.next
            else:
                flag = True
                break
        return flag

上面的做法更多的是一个trick,一般的做法是用快慢指针来做:

def isloop(head):
	if head == None or head.next == None:
		return None
	#初始化slow与fast为指向链表的第一个结点
	slow = head.next
	fast = head.next
	while fast!=None and fast.next!=None:
		slow = slow.next
		fast = fast.next.next
		if slow == fast:
			return True
	return False

你可能感兴趣的:(Pytorch,编程练习)