解题思路


使用了链表交换的概念,引入的temp节点作为链表交换并确定交换起始位置。

图解:

image-yfodbeeu.png

实现代码


class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode dummyHead = new ListNode(0);
        dummyHead.next = head;
        ListNode temp = dummyHead;
        while (temp.next != null && temp.next.next != null) {
            ListNode node1 = temp.next;
            ListNode node2 = temp.next.next;
            temp.next = node2;
            node1.next = node2.next;
            node2.next = node1;
            temp = node1;
        }
        return dummyHead.next;
    }
}

复杂度分析


  • 时间复杂度:O(N)
  • 空间复杂度:O(1)