文章目录
https://leetcode-cn.com/problems/swap-nodes-in-pairs/
链表交换节点的题目,还有 进阶题 25. K 个一组翻转链表 https://leetcode-cn.com/problems/reverse-nodes-in-k-group/
24. 两两交换链表中的节点
按照递归就能顺利写出
def swapPairs(self, head: ListNode) -> ListNode:
1 边界条件
2 一般情况下需要执行的操作
3 返回
假设swapPairs能够返回一个链表两两交换后的首结点
- 边界条件 —— 显然 head为空或者head.next为空时,直接返回head
- 操作 —— 我们假设了swapPairs的功能,那么当我们调用
tail = swapPairs(head.next.next)
的时候,函数会返回一个交换后的链表,首结点存储在tail中,那么需要执行的操作就是交换head和head.next两个结点,交换结点的代码可以很简单的写出 - 返回,显然我们应该返回head.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: ListNode) -> ListNode:
# 如果head不存在 返回None
if not head:
return None
if not head.next:
return head
# 交换后面的n-2个结点
tail = self.swapPairs(head.next.next)
# 交换当前结点
t = head.next
t.next = head
head.next = tail # 将当前结点指向交换后的链表首结点tail
return t
25.
25题很早之前做过了,一时想不起来,先空着