冉宝的每日一题--链表题

本文介绍了如何解决LeetCode上的链表题目,包括如何迭代和递归地反转链表,以及利用快慢指针检测环形链表。作者强调了对迭代反转链表写法的记忆,并讨论了相关的时间和空间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近发现leetcode真的是最局限我的东西,我一定要在周一之前做到300t。
加油!
链表题冲刺!

反转链表

https://leetcode-cn.com/problems/reverse-linked-list/

迭代写法 --要背下来

def reverseList(head):
	pre = None
	cur = head
	while cur:
		next_node = cur.next 
		cur.next = pre 
		pre = cur 
		cur = next_node
	return pre

注意最后return的是pre

  • 时间复杂度:O(n) ,其中n 的你链表长度,需要遍历一次
  • 空间复杂度: O(1)

递归写法

假设链表剩下的部分已经被反转,如何反转前面的部分

def reverseList(head):
	# 退出条件
	if not head or not head.next: 
		return head 
	new_head = reverse(head.next)
	head.next.next = head # 这个时候head还是指向末尾
	head.next = None
	return new_head
  • 时间复杂度: O(n) ,其中n是链表的长度,需要对链表中每个节点反转,
  • 空间复杂度:O(n) 递归调用的栈空间 O(n)

环形链表

快慢指针

快指针走两步,慢指针走一步
假设时间为t,快指针走了2t,慢指针走了t
假设不重复的路径长度为l1,环的长度为l2
相遇说明 快指针夺走了整数圈
2t - t = kl2
2t = l1 + m
l2 + l3
t = l1 + n* l2 +l3

class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        if not head or not head.next or not head.next.next:
            return False
        fast = head 
        slow = head 
        while fast:
            if fast.next and fast.next.next:
                slow = slow.next
                fast = fast.next.next 
            else:
                return False
            
            if slow == fast:
                return True 
        return False
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值