24. Swap Nodes in Pairs

public class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head==null||head.next==null)
            return head;
        ListNode ret=head.next;
        head.next=swapPairs(head.next.next);
        ret.next=head;
        return ret;
    }
}

 Iteration

public class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode preNode=new ListNode(0);
        preNode.next=head;
        ListNode p=preNode;
        while(p.next!=null&&p.next.next!=null)
        {
            ListNode q=p.next.next;
            p.next.next=q.next;
            q.next=p.next;
            p.next=q;
            p=p.next.next;
        }
        return preNode.next;
    }
}
原文地址:https://www.cnblogs.com/asuran/p/7579549.html