[leetcode] Linked List Cycle

来源:互联网 发布:韩语歌音译软件 编辑:程序博客网 时间:2024/06/05 00:43

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

Follow up:

Can you solve it without using extra space?

思路:双指针法,如果有cycle,快得指针总能赶上慢的指针(会不会跳过慢的指针?不会,因为每次快的指针只比慢的指针快一步)

# Definition for singly-linked list.# class ListNode:#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution:    # @param head, a ListNode    # @return a boolean    def hasCycle(self, head):        slow = head        fast = head        while fast != None and fast.next != None:            fast = fast.next.next            slow = slow.next            if fast != None and slow != None and fast.val == slow.val:                return True        return False


0 0
原创粉丝点击