最近发现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 + ml2 + 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