题目 
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
示例 1:
输入:head = [1,2,3,4]
输出:[2,1,4,3]1
2
2
示例 2:
输入:head = []
输出:[]1
2
2
示例 3:
输入:head = [1]
输出:[1]1
2
2
提示:
- 链表中节点的数目在范围 
[0, 100]内 0 <= Node.val <= 100
题解 
java
public ListNode swapPairs(ListNode head) {
    // 新链表
    ListNode result = new ListNode(0);
    // 新链表遍历指针
    ListNode cursor = result;
    while (null != head) {
        ListNode previous = head;
        ListNode next = head.next;
        // 节点数量为奇数
        if (null == next) {
            head = null;
        } else {
            // 头节点移动2位
            head = next.next;
            // 节点数量为偶数 交换节点
            // 将第二个节点移动到第一个
            // 置空后置节点
            next.next = null;
            cursor.next = next;
            cursor = cursor.next;
            // 将第一个节点移动到第二个
            // 置空后置节点
            previous.next = null;
        }
        cursor.next = previous;
        cursor = cursor.next;
    }
    return result.next;
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31