24. 两两交换链表中的节点 【递归】
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
输入:head = [1,2,3,4] 输出:[2,1,4,3]

思路:递归

from typing import Optional
# 创建链表
def create_linked_list(lst):
if not lst:
return None
head = ListNode(lst[0])
current = head
for val in lst[1:]:
current.next = ListNode(val)
current = current.next
return head
# 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
t = self.swapPairs(head.next.next)
p = head.next
p.next = head
head.next = t
return p
if __name__ == '__main__':
s = Solution()
lst = [1, 2, 3, 4]
head = create_linked_list(lst)
res = s.swapPairs(head)
print(res)