JAVA--------------Easy Version To Understand!!!!


  • 0
    H
      public static  ListNode swapPairs(ListNode head) {
    	if(head==null)
          return null;
    	ListNode headNode=new ListNode(0);
    	headNode.next=head;
    	head=headNode;
    	ListNode before=head,first=before.next,second=first.next,first1;
    	while(first!=null&&second!=null){
    		before.next=second;
    		first1=second.next;
    	    second.next=first;
    	    first.next=first1;
    	    before=first;
    	    first=first1;
    	     if(first!=null)
    	    second=first.next;
    	}
    	
    	return head.next;
    }

  • 0
    S

    that if block shoud be out side the while block?


  • 0
    H

    what are you saying????


  • 1
    X

    Java solution

       public ListNode swapPairs(ListNode head) {
         
    	if (head == null || head.next == null) return head;
    
    	ListNode first = head;
    	ListNode second = head.next;
    	ListNode link = null;
    	head = second;
    
    	while(first != null && second != null) {
    
    	    // Interchange the first and second in the pair
    	    first.next = second.next;
    	    second.next = first;
    	    
    	    // Link the previous pair
    	    if (link != null) 
    		link.next = second;
    
    	    link = first;
    
    	    // Got to the next pair
    	    first = first.next;
    	    if (first != null) 
    		second = first.next;
    	    
    	}
    
    	return head;
    
       
        }

  • 0
    P

    simple concise and meaningful


Log in to reply
 

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