两两交换链表中的节点
首先假设子问题已经解决了,由于是两两交换节点,因此我们需要预留出两个节点出来才行,之前使用递归对链表求解的时候都是只需要操作head节点即可,但是这里要求两个节点交换,因此需要head和head.next两个节点,因此子问题的输入就是head.next.next了
最后写成代码如下
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head is None or head.next is None:
return head
sr = self.swapPairs(head.next.next)
t = head.next
t.next = head
head.next = sr
return t