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
相关推荐
HY小海1 小时前
【数据结构】双链表
c语言·开发语言·数据结构·学习
I AM_SUN2 小时前
994. 腐烂的橘子
数据结构·c++·算法·leetcode·职场和发展
bai_lan_ya2 小时前
数据结构之串
数据结构
小狗祈祷诗2 小时前
day18-数据结构引言
c语言·数据结构
序属秋秋秋3 小时前
《数据结构初阶》【堆 + 堆排序 + TOP-K】
c语言·数据结构·c++·笔记
咩咩觉主13 小时前
c#数据结构 线性表篇 非常用线性集合总结
开发语言·数据结构·unity·c#·游戏引擎·程序框架
zhangpeng45554794015 小时前
数据结构-非线性结构-二叉树
数据结构
AllenO.o17 小时前
Redis五种数据结构详解
java·数据结构·数据库·redis·缓存
重生之后端学习17 小时前
day23-集合(泛型&Set&数据结构)
java·开发语言·数据结构·算法
焜昱错眩..18 小时前
代码随想录训练营第二十一天 |589.N叉数的前序遍历 590.N叉树的后序遍历
数据结构·算法