Simple Iterative Java Solution


  • 4
    V
    class Solution {
        public ListNode swapPairs(ListNode head) {
            if(head == null || head.next == null){
                return head;
            }
            ListNode current = head;
            head = head.next; // new head will be next to head
            while(current != null && current.next != null){
                ListNode nextToCurrent = current.next;
                ListNode temp = nextToCurrent.next;
                nextToCurrent.next = current;
                if(temp != null && temp.next != null){
                    current.next = temp.next;
                } else {
                    current.next = temp;
                }
                current = temp;
            }
            return head;
        }
    }
    

Log in to reply
 

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