24. Swap Nodes in Pairs 发表于 2021-12-18 Recursion12345678910111213class Solution { public ListNode swapPairs(ListNode head) { if (head == null || head.next == null) { return head; } // nodeA -> nodeB -> ... ListNode nodeA = head, nodeB = head.next; nodeA.next = swapPairs(nodeB.next); nodeB.next = nodeA; return nodeB; }} Iterate123456789101112131415161718192021222324252627282930class Solution { public ListNode swapPairs(ListNode head) { ListNode dummyHead = new ListNode(-1, head); ListNode pre = dummyHead; // dummyHead -> nodeA -> nodeB -> nodeC -> ... // pre -> nodeA -> nodeB -> nodeC -> ... while (pre.next != null) { ListNode nodeA = pre.next; ListNode nodeB = nodeA.next; if (nodeB == null) { break; } ListNode nodeC = nodeB.next; nodeB.next = nodeA; nodeA.next = nodeC; // dummyHead -> nodeB -> nodeA -> nodeC -> ... // pre -> nodeB pre.next = nodeB; // dummyHead -> nodeB -> nodeA -> nodeC -> ... // pre pre = nodeA; } return dummyHead.next; }} Reference24. Swap Nodes in Pairs