import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
    public ListNode swapPairs (ListNode head) {
        // write code here
        if(head==null||head.next==null) {
			return head;
		}
		ListNode newhead=head.next;
		head.next=swapPairs(newhead.next);
		newhead.next=head;
		return newhead;
    }
}

使用递归的做法,开头先设置截止条件,如果链表为空或者当前结点为尾结点时停止,因为要交换结点,所以我们需要把两个结点提取出来,让newhead.next指向head,让head.next指向它后面的结点,那它后面的结点是什么呢,其实就是递归返回的结果,我们在递归的时候其实就相当于把新链表传进去了,那么返回的肯定是新链表的新头结点,这样就能解决问题