利用反转链表的思路加上每 k 个 节点的限制,对整个链表进行递归处理, 得出最终的结果
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param head ListNode类
# @return ListNode类
#
class Solution:
def reverse(self, s: ListNode, e: ListNode) -> ListNode:
t = None
while s != e:
n = s.next
s.next = t
t = s
s = n
return t
def reverseK(self, head: ListNode, k: int) -> ListNode:
s = head
for i in range(k):
if not s:
return head
s = s.next
b = self.reverse(head, s)
head.next = self.reverseK(s, k)
return b
def swapLinkedPair(self , head: ListNode) -> ListNode:
# write code here
return self.reverseK(head, 2)