leetcode141环形路径

leetcode141 Linked List Cycle

Posted by BY on March 22, 2019

前言

新的一年,好好学习。尝试用python写写代码。

正文

问题来源

本问题来自leetcode上的141题。

问题描述

给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。

示例 1:

输入:head = [3,2,0,-4], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。

分析:

回溯法 用一个path记录走过的路径,当回溯到上一层时,退回路径。当路径和与目标值相同时,拷贝一份path,加入到结果集中。

# 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
        """
        a = head
        b = head
        while a and b and b.next:
            a = a.next
            b = b.next.next
            if a == b:
                return True
        return False

总结:

勤思考。

结语

不管怎么样好好加油。