给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
    你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

    示例:
    给定 1->2->3->4, 你应该返回 2->1->4->3.
    法一:迭代,4步骤
    24. 两两交换链表中的节点 - 图1

    1. /**
    2. * Definition for singly-linked list.
    3. * public class ListNode {
    4. * int val;
    5. * ListNode next;
    6. * ListNode(int x) { val = x; }
    7. * }
    8. */
    9. class Solution {
    10. public ListNode swapPairs(ListNode head) {
    11. if (head == null || head.next == null) return head;
    12. ListNode node = new ListNode(0);
    13. node.next = head;
    14. ListNode res = node;
    15. while (head != null && head.next != null) {
    16. node.next = head.next;
    17. head.next = head.next.next;
    18. node.next.next = head;
    19. node = node.next.next;
    20. head = head.next;
    21. }
    22. return res.next;
    23. }
    24. }

    24. 两两交换链表中的节点 - 图2