最近在学习递归的专栏看到这样的一个题目,题目很简单就是将单双位置的结点进行交换,第一和第二,第三和第四……很简单的思想就是设置一个标识利用循环完成,每次做完交换就就将标识移到下一个位置,同样的在这里利用递归来实现,代码看上去会十分简洁。

/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */
class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null)
            return head;
        ListNode temp = head.next;
        head.next = temp.next;
        temp.next = head;
        head.next = swapPairs(head.next);
        return temp;
    }
}