Java Solution; ~O(n) running time, O(1) memory, 4ms.


  • 1
    S
    public class Solution {
      public ListNode swapPairs(ListNode head) {
        if (head == null) return null;
        if (head.next == null) return head;
    
        ListNode n = head;
        ListNode m = head.next.next;
    
        head = head.next;
        head.next = n;
        head.next.next = swapPairs(m);
    
        return head;
      }
    }
    

Log in to reply
 

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