Swap nodes in pairs clear Java Solution 276 ms


  • 0
    V
    public class Solution {
     public ListNode swapInPairs(ListNode head,ListNode prev){
        if(head==null
            ||head.next==null){
            try{
                head.next=prev;
                prev.next=null;
                return head;
            }catch (NullPointerException e){
                return prev;
            }
        }
        ListNode t=head.next;
        head.next=prev;
        prev.next=swapInPairs(t.next,t);
        return head;
    }
    public ListNode swapPairs(ListNode head) {
        return head!=null?swapInPairs(head.next,head):null;
    }
    

    }


  • 0
    C

    Great solution. However, try catch may not be necessary since we can use 3 pointers.

    public class Solution {
        public ListNode swapPairs(ListNode head) {
            if (head == null || head.next == null) return head;
            ListNode newHead = head.next, prev = new ListNode(0), cur = head, next = cur.next;
            while (next != null && next.next != null) {
                cur.next = next.next;
                next.next = cur;
                prev.next = next;
                prev = cur;
                cur = prev.next;
                next = cur.next;
            }
            if (next == null) return newHead;
            cur.next = null;
            next.next = cur;
            prev.next = next;
            return newHead;
        }
    }

  • 0
    V
    This post is deleted!

  • 0
    V
    public class Solution {
    public ListNode swapPairs(ListNode head){
        if(head==null)
            return head;
        ListNode prev,next,newHead=head.next!=null?head.next:head;
        while(head!=null&&head.next!=null){
            next=head.next;
            prev=next.next;
            next.next=head;
            head.next=prev!=null&&
                      prev.next!=null?prev.next:prev;
            head=prev;
        }
        return newHead;
    }
    

    new Solution in 220 ms


  • 0
    V

    Thanks:) what about solution below?220ms


Log in to reply
 

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