Java iterative solution with comments


  • 0
    E
    public class Solution {
    public ListNode swapPairs(ListNode head) {
        // for simplicity lets name the nodes as ([a] -> [b]) -> ([a] -> [b]) ...
        //         end result should then look like ([b] -> [a]) -> ([b] -> [a]) ...
        ListNode nodeA = head;
        ListNode nodeB = nodeA != null ? head.next : null;
        ListNode previousNodeA = null;
        while(nodeA != null && nodeB != null) {
            // swap current node with its next node and save current node as previous node
            if (previousNodeA != null) {
                previousNodeA.next = nodeB;
            } else {
                head = nodeB;
            }
            
            ListNode nextNodeA = nodeB.next;
            nodeB.next = nodeA;
            
            // now it looks like [a]) -> ([b] <-> [a]) _ ([a] -> [b])...
            previousNodeA = nodeA;
            nodeA = nextNodeA;
            nodeB = nodeA != null ? nodeA.next : null;
        }
        
        // make sure to fix the [a] <-> [b] loop to point to next [a] or null
        if (previousNodeA != null) {
            if (nodeA != null) {
                previousNodeA.next = nodeA;
            } else {
                previousNodeA.next = null;
            }
        }
        
        return head;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.