Iterative solution, O(n) time and O(1) space


  • 0
    A
    public ListNode SwapPairs(ListNode head) {
            ListNode newHead = null;
                if (head == null)
                {
                    return head;
                }
                else if (head.next == null)
                {
                    return head;
                }
                else
                {
                    newHead = head.next;
    
                    ListNode current = head;
                    ListNode next = current.next;
                    ListNode prev = null;
                    while (next != null)
                    {
                        // interchange the pointers between the current two nodes, e.g. 1 -> 2 becomes 2->3
                        current.next = next.next;
                        next.next = current;
    
                        if (prev != null)
                        {
                            prev.next = next;
                        }
                        prev = current;
                        // advance next and current.
                        current = current.next;
                        if (current == null)
                        {
                            break;
                        }
    
                        next = current.next;
                    }
                }
    
                return newHead;
            
        }
    

Log in to reply
 

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