My simple < 4ms Java solution


  • 0
    R
    public class Solution {
    
        public ListNode swapPairs(ListNode head) {
            if (head == null || head.next == null) {
                return head;
            }
    
            ListNode dummyHead = new ListNode(0);
            dummyHead.next = head;
            head = dummyHead;
            ListNode middle, right;
    
            while (head.next != null && head.next.next != null) {
                middle = head.next;
                right = head.next.next;
    
                head.next = right;
                middle.next = right.next;
                right.next = middle;
    
                head = head.next.next;
            }
            return dummyHead.next;
        }
    }
    

Log in to reply
 

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