Clean Java Solution

  • 0

    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 || == null) return head;
            ListNode p = null;
            ListNode c = head;
            ListNode n = null;
            while(c != null){
                n =;
                if(n == null) return head;
       = c;
                if(p == null) head = n; else = n;
                p = c;
                c =;
            return head;

Log in to reply

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