Simple solution without confusing .next.next


  • 0
    A
    public ListNode swapPairs(ListNode head) {
            ListNode dummyNode = new ListNode(0);
            dummyNode.next = head;
    
            ListNode third = null;
            ListNode second = null;
            ListNode first = null;
    
            int counter = 0;
            ListNode current = dummyNode;
    
            while (current != null) {
                first = current;
                if (counter % 2 == 0 && counter != 0) {
                    second.next = first.next;
                    first.next = second;
                    third.next = first;
                    current = second.next;
                } else {
                    third = second;
                    second = first;
                    current = current.next;
                }            
                counter++;
            }
            return dummyNode.next;
        }
    

Log in to reply
 

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