两两交换链表中的节点
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)
示例:
输入: head = [1,2,3,4]
输出: [2,1,4,3]
提示:
- 链表中节点的数目在范围 [0, 100] 内
- 0 <=
Node.val
<= 100
递归
- 用
head
表示原始链表的头节点 - 用
newHead
表示新的链表的头节点 - 令
head.next = swapPairs(newHead.next)
,则交换后的新的头节点为head
的下一个节点 - 然后令
newHead.next = head
,即完成了所有节点的交换 - 终止条件是链表中没有节点,或者链表中只有一个节点
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = head.next;
head.next = swapPairs(newHead.next);
newHead.next = head;
return newHead;
}
}