My accepted Java solution with a CONSTANT SPACE COMPLEXITY without using recursion


  • 0

    '''
    public ListNode swapPairs(ListNode head) {
    if (head == null || head.next == null) return head;
    ListNode even=head.next.next, odd=head, curr=head.next;
    head = head.next;
    while (curr != null) {
    curr.next = odd;
    if (even == null || even.next == null) {odd.next = even; return head;}
    else odd.next = even.next;
    curr = even.next;
    odd = even;
    even = curr.next;

    	}
        return head;
    }
    

    '''


Log in to reply
 

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