链表两两交换

递归大法好啊,遇事不决多画图,准没毛病。

  1. 把需要交换的两个节点的第一个节点传入递归
  2. 判断其自身是否为空(节点数偶数)、其下一节点是否为空(节点数奇数),任何一个为空都没有交换的意义。
  3. 接下来就是简单的交换了,把需要返回的节点返回即可。
class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode second = head.next;
        ListNode third = second.next;
        second.next = head;
        head.next =  swapPairs(third);
        return second;
    }
}

原文地址:https://www.cnblogs.com/bokers/p/15591130.html