前言
本文章记录了算法题 两两交换链表中的节点 的递归解法
题目
思路
对当前节点head的后两个节点的链表L1进行节点两两交换,再记录下head的next节点,并对head和head.next节点两两交换,最后添加到交换后的链表L1
图片解析
函数头
swapPairs (head.next.next)
函数体
newhead= head.next;
newhead.next=head;
head.next=tmp;
return newhead;
递归出口
if (head == null || head.next == null) return head
//无论节点个数为偶数还是奇数,递归到最后遇到空节点返回head
代码编写
class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null || head.next==null) return head;
ListNode tmp=swapPairs(head.next.next);
ListNode newhead= head.next;
newhead.next=head;
head.next=tmp;
return newhead;
}
}
总结
递归算法题的核心思路:找到子问题和递归出口
本题的子问题:两两交换节点
递归出口:递归到空节点返回head
文章到这结束啦,感谢阅读~
如果你觉得文章写的还不错,记得点赞收藏评论三连~ ❤