My java solution O(1) space O(n) time


  • 0
    
        public ListNode swapPairs(ListNode head) {
            if(head == null || head.next == null){
                return head;
            }
            ListNode dummynode = new ListNode(0);
            dummynode.next = head;
            ListNode cur = dummynode;
            ListNode l1 = dummynode.next;
            ListNode l2 = l1.next;
            while(l1 != null && l2!= null){
                cur.next = l2;
                l1.next = l2.next;
                l2.next = l1;
                
                cur = l1;
                l1 = l1.next;
                if(l1 == null){
                    break;
                }
                l2 = l1.next;
            }
            
            return dummynode.next;
        }
    
    

Log in to reply
 

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