力扣 24题 两两交换链表中的节点


Question 24-swap nodes in pairs

解题思路

简单递归,如果当前节点没有后继,就返回当前节点(因为没有节点和它组成 pair 了)。否则,使当前节点的后继为自己后继的后继,并让当前节点的原后继成为它的前驱。

代码

class Solution {
    public ListNode swapPairs(ListNode head) {

        if (null == head)   return null;
        if (null == head.next)  return head;

        head.next.next = swapPairs(head.next.next);

        ListNode next = head.next;
        head.next = next.next;
        next.next = head;

        return next;
    }
}