leetcode141-- Linked List Cycle(判断链表是否有环)

leetcode141-- Linked List Cycle(判断链表是否有环)

题目

这个的想法就是用快慢指针的办法,一个walker,一个runner, walker一次走一步,runner一次走两步,然后如果它们能够相见的话说明有环。

# 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
        """
        walker = head
        runner = head
        while (runner != None and runner.next != None):
            walker = walker.next
            runner = runner.next.next
            if(walker==runner):
                return True
        return False

打赏,谢谢~~

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,多谢支持~

打开微信扫一扫,即可进行扫码打赏哦