[每日一题]141.Linked List Cycle(链表)

1.这是一个判断 链表中是否有环 的题目。

链接:https://leetcode.com/problems/linked-list-cycle/

141.Linked List Cycle.png

题目的意思就是输入一个链表,然后判断链表是否构成了环状结构。
这里有三个思路解决这个问题:

1.在限定时间内不断的向后跑,判断是否能得到等于None值。如果可以得到,判断它没环;如果得不到,有环。
2.使用键值对,记录这个Node。ps:其实集合(Set就可以,插入错误,直接判断有环)
3.使用长短指针的思路。这个待会画图解释,就是一个快车,一个慢车,如果他们两能相遇的话,判断是有环的。

2.题解:

这里给出后面两个思路的代码:
思路2:

class Solution:
    # 2- 使用字典记录
    def hasCycle(self, head):
        dict_list = {}
        i = 0
        node = head
        while node:
            if node in dict_list:
                # return dict_list[node] # 这里可以直接返回在哪个节点形成环
                return True
            else:
                dict_list[node] = i  # 记录键值对
                i += 1
                node = node.next
        return False

思路3:

画图解释:


141.Linked List Cycle.jpg
  # 3- 使用长短指针记录
    def hasCycle(self, head):
        fast = slow = head
        while slow and fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if slow is fast:
                return True
        return False

3.完整代码

查看链接:
https://github.com/Wind0ranger/LeetcodeLearn/blob/master/1-List/141-linked-list-cycle.py

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容