小黑用两种方法独立做出一道困难等级题目,思维训练不能停!!好爽啊
小黑代码–递归法
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
t = head
i = 1
# 确保后面有k个结点
while t and i < k:
i += 1
t = t.next
if not t:
return head
# 开始对后面的结点深度递归,并返回
after = self.reverseKGroup(t.next, k)
# 逆转从head到t的链表
l = head
r = head.next
# 开始进行逆转操作
while l != t:
temp = r.next
r.next = l
l = r
r = temp
# 将逆转后的结果回溯
head.next = after
return t
小黑代码–继续死磕非递归法
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverse(self, head, k):
temp = head
# 计数器
num = 0
while temp and num < k:
temp = temp.next
num += 1
# 没有k个结点
if num < k:
return head, None
# 开始逆转序列
l = head
r = head.next
while r != temp:
t = r.next
r.next = l
l = r
r = t
head.next = temp
return l, head
def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
# 设置附加头结点
add_node = ListNode()
add_node.next = head
# 设置指针,指向下一个需要被逆转序列的前置结点
left = add_node
# 开始迭代
while left:
# 逆转序列的前置结点
t = left.next
h, t = self.reverse(t, k)
# 将处理后的序列链接到链表上
left.next = h
left = t
return add_node.next
非递归迭代法
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
# 翻转链表
def reverse(self, head):
# 初始化前驱结点指针
pre = None
# 当前结点指针
cur = head
while cur:
t = cur.next
cur.next = pre
pre = cur
cur = t
return pre
def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
# 额外结点
add_node = ListNode()
add_node.next = head
# 指向需要逆转序列的前驱结点指针
tail = add_node
while tail:
# 初始化指针,计算出子序列的尾指针
t = tail
# 寻找尾指针
# print('========================')
for i in range(k):
t = t.next
if not t:
return add_node.next
# print(t.val)
# 该子序列起点
start = tail.next
# 下一个子序列起点
next_ = t.next
# 将该子序列的尾指针的next置空,便于逆转操作
t.next = None
# 链接逆转后的序列
tail.next = self.reverse(tail.next)
# print('tail.next:', tail.next, 't', t.val)
# 子序列头结点start逆转后变成尾结点,将其链接到后面的序列
start.next = next_
# 更新tail指针
tail = start
return add_node.next
小黑生活(由于手机互传误删了所有照片,该内容只能从朋友圈和群聊等搜集当时的照片,不全但也要坚持记录)
动车上发烧出了一晚上汗,喝了好多水,有了些好转
乘坐苏州地铁到达北寺塔,平江路吃早餐
尝一尝早茶蟹黄面,太贵了100+
狮子林游玩,小黑跟着小红书挨个地方看
去拙政园也转转,跟着小红书讲解打卡每一个景点,增强自身文化修养
去北寺塔地铁站与舞花侠碰面,买根淀粉肠
跟舞花侠碰面啦,带我吃好吃的,蟹黄肉汤包,苏式生煎
一起喝喜茶,领取半程马拉松物资
七里山塘景区转转,欣赏夜景
前往苏州CBD,欣赏音乐喷泉