假设我们有一个单链表,还有另一个值k,我们必须反转每k个连续的节点组。
因此,如果输入类似于List = [1,2,3,4,5,6,7,8,9,10],k = 3,则输出将为[3,2,1,1,6,5 ,4,9,8,7,10,]
为了解决这个问题,我们将遵循以下步骤-
tmp:=一个值为0的新节点
tmp的下一个:=节点
上一页:= null,curr:= null
lp:= temp,lc:= curr
cnt:= k
虽然curr不为空,但是
以下:=下一个
下一个curr:=上一页
上一页:= curr,curr:=以下
cnt:= cnt-1
上一页:=空
当cnt> 0并且curr不为null时,执行
下一个lp:=上一个,下一个lc:= curr
lp:= lc,lc:= curr
cnt:= k
返回tmp的下一个
让我们看下面的实现以更好地理解-
class ListNode: def __init__(self, data, next = None): self.val = data self.next = next def make_list(elements): head = ListNode(elements[0]) for element in elements[1:]: ptr = head while ptr.next: ptr = ptr.next ptr.next = ListNode(element) return head def print_list(head): ptr = head print('[', end = "") while ptr: print(ptr.val, end = ", ") ptr = ptr.next print(']') class Solution: def solve(self, node, k): tmp = ListNode(0) tmp.next = node prev, curr = None, node lp, lc = tmp, curr cnt = k while curr: prev = None while cnt > 0 and curr: following = curr.next curr.next = prev prev, curr = curr, following cnt -= 1 lp.next, lc.next = prev, curr lp, lc = lc, curr cnt = k return tmp.next ob = Solution()head = make_list([1,2,3,4,5,6,7,8,9,10]) print_list(ob.solve(head, 3))
[1,2,3,4,5,6,7,8,9,10], 3
输出结果
[3, 2, 1, 6, 5, 4, 9, 8, 7, 10, ]