Time :O(n) Space O(1)


  • 0
    A
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode swapPairs(ListNode head) {      
    
            ListNode curr;
            ListNode temp;        
            ListNode Stemp;
            
            Boolean set = false;
            
            curr = null;        
            temp = null;        
            Stemp = null;
            
            if (head == null) return head;
            
            if(head.next!= null){
                curr = head;    
                head = head.next;
            }
            
            while(curr!= null && curr.next!= null){
                temp = curr.next;
                curr.next = temp.next;
                temp.next = curr;
                
                if(!set) {
                head = temp;
                set = true;
                }
                
                     
                if(curr.next == null) break;            
                if(curr.next.next == null) break;
    
                Stemp = curr.next;            
                curr.next = Stemp.next;
                curr = Stemp;
                
            }
            return head;
            ```
            
        }
    }

Log in to reply
 

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