141. 环形链表

python 复制代码
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        # # 方法1 :Hash 表
        # seen = set()
        # p = head 
        # # p有可能上来就是空的
        # while p:
        #     if p not in seen:
        #         seen.add(p)
        #         p = p.next 
        #     else: # 存在环
        #         return True
        # return False 
        

        # 方法2:快慢指针
        # 如果有环的话
        # 快指针每次移动两个,慢指针每次只移动一格
        # 快指针先进入环,慢指针后进入环,那快慢指针总有相遇的时候
        # 相遇的时候,那快指针就比慢指针多跑了n圈


        fast = head 
        slow = head 
        
        # 因为fast总是跑的比slow快,所以只需要判断fast, fast.next就行
        while fast and fast.next:
            fast = fast.next.next 
            slow = slow.next

            if fast == slow:
                return True 
        return False


            
        

自己构建环形链表

python 复制代码
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

# 构建环形链表的函数
def build_cyclic_list(values, pos):
    if not values:
        return None

    # 创建链表节点
    head = ListNode(values[0])
    current = head
    for value in values[1:]:
        current.next = ListNode(value)
        current = current.next

    # 使链表成为环形
    if pos != -1:
        tail = head
        for _ in range(pos):
            tail = tail.next
        current.next = tail

    return head

# 使用示例
values = [3, 2, 0, -4]
pos = 1  # 链表尾部连接到索引为1的节点,即第二个节点
head = build_cyclic_list(values, pos)

那就是head, head.next实际上是指向内存的地址

所以对于[ 3, 2, 4, 1, 2, 4, 1] pos = 1的环形链表,用set集合的话,也就是哈希表的话,第一个2和后面的2实际上是不一样的,因为他们的next值都不一样!

python 复制代码
# 下面是我自己又写了一遍,大致逻辑差不多
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None
def build_cyclic_list(value: list, pos: int):
    # 要先对val进行判断,是否有元素, 这一步很重要
    if not value:
        return None

    # 在实例化class的时候,就需要传入init里面的参数
    head = ListNode(value[0])
    # head.val = value[0]

    p = head
    # 构建链表
    for i in range(1, len(value)):
        p.next = ListNode(value[i])
        # p.next.val = value[i]
        p = p.next

    # 处理环形,也就是链表的尾部应该指向哪里
    tail = head
    count = 0
    while count < pos:
        tail = tail.next
        count += 1
    p.next = tail

    return head
相关推荐
大母猴啃编程2 小时前
C++基础---类和对象(上)
c语言·开发语言·数据结构·c++·学习·算法·青少年编程
2301_804774493 小时前
算法学习1
java·数据结构·算法
程序员阿鹏4 小时前
HashMap为什么线程不安全?如何实现线程安全
java·开发语言·数据结构·安全·eclipse·intellij-idea
Amor风信子5 小时前
华为OD机试真题---计算三叉搜索树的高度
数据结构·算法·华为od
NMBG225 小时前
[数据结构] 二叉树题目(一)
java·数据结构·算法·leetcode
小川_wenxun5 小时前
Java:插入排序
数据结构·算法·排序算法
陈小唬5 小时前
算法——冒泡排序
数据结构·算法·排序算法
-$_$-6 小时前
【LeetCode HOT 100】详细题解之链表篇
leetcode·链表
yi碗汤园7 小时前
【一文读懂】C#如何实现通用的排序功能
开发语言·数据结构·算法·c#
AutoAutoJack7 小时前
C# 字符串(String)的应用说明一
开发语言·数据结构·算法·架构·c#