Clean Java Solution


  • 0
    N

    I found out after solving few problems of this sort, the best way is to work out few examples on paper (for ex: 1-->2-->null, 1-->2-->3-->null).
    Then, focus on the main logic, that is first deal with .....-->a--->b--->c--->......, then address the corner cases. Please let me know if you guys have a better way to deal with.

    class Solution {
        public ListNode swapPairs(ListNode head) {
         
            if(head == null || head.next == null) return head;
            
            ListNode p = null;
            ListNode c = head;
            ListNode n = null;
            
            while(c != null){
                n = c.next;
                if(n == null) return head;
                c.next = n.next;
                n.next = c;
                if(p == null) head = n; else p.next = n;
    
                p = c;
                c = c.next;
            }
           
            return head;
        }
    }
    

Log in to reply
 

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