https://leetcode.com/problems/reverse-nodes-in-k-group/
我愿称之为,最强链表操作题。
没有花里胡哨的东西,思路也很清楚,就是个模拟题,但是如何优雅的写出来,同时考虑边界情况,不是那么容易。
个人解答
# 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: ListNode, k: int) -> ListNode:
dummy = ListNode(0, head)
def reverse(prev, tail, k):
p = prev.next
newNext = tail
for i in range(k):
nxt = p.next
p.next = newNext
newNext = p
p = nxt
newTail = prev.next
prev.next = newNext
return newTail
cnt = 0
p = dummy.next
prev = dummy
while p:
cnt += 1
p = p.next
if cnt % k == 0:
tail = reverse(prev, p, k)
prev = tail
return dummy.next
题目分析
没什么好说的,就是模拟。
注意定义好,每个部分负责哪些指针,保证所有指针指向正确的地方。