判读一个链表中是否有环(Leetcode141--环形链表)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/EngineerHe/article/details/99747355

Leetcode141–环形链表

给定一个链表,判断链表中是否有环。

编程语言:python

作者:黑暗主宰

邮箱:[email protected]

Leetcode141–环形链表

题目描述

原题链接:

​ https://leetcode-cn.com/problems/linked-list-cycle/ (中文)

​ https://leetcode.com/problems/linked-list-cycle/ (英文)

题目描述:

给定一个链表,判断链表中是否有环。

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

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

img

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

img

示例3:
  输入:head = [1], pos = -1
  输出:false
  解释:链表中没有环。

img

解题思路

方法1:哈希表

对于链表而言,不像数组那样可以索引到下标,所以对于判读一个链表是不是有环,因为链表中每个结点的地址是唯一,最直观的想法是,遍历的过程中把地址存入一个哈希表中,然后要是有None就表示没有环,要是遍历的过程中发现哈希表中已经存在了某个结点的地址,就表示该链表是环形链表。

# 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
        """
        hash_value = []
        while head != None:
            if head in hash_value:
                return True
            else:
                hash_value.append(head)
            head = head.next
        return False

通过上述的代码可以看到,使用哈希表的方法的话,需要额外的空间去存储,空间复杂度是 O ( n ) O (n) ,如果是大的数据的话,很浪费内存。

方法2:双指针的方法

同样是遍历的方法,使用双指针的空间复杂度就是 O ( 1 ) O (1) ,具体操作是:两个指针分为快指针和慢指针,慢指针每次走一步,快指针每次走两步,这样的话,如果不是环链表,快指针遇到 None就可以结束,否则的话,快指针肯定会追上慢指针,这里画个动态地图演示一下;

在这里插入图片描述

下面是动态规划方法的代码:

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

猜你喜欢

转载自blog.csdn.net/EngineerHe/article/details/99747355
今日推荐