Can Anyone Tell me Whats wrong with this code in Java


#1

public class Solution {
public ListNode solve(ListNode A) {

    if( A == null || A.next == null ) return A ;
    ListNode temp1 = A ; 
    ListNode temp = A ;
  
  while( temp.next != null && temp1.next != null )
   {
    if( temp.val == 1  )
    {
        temp = temp.next ;
    }
      else 
         {
              swap( temp ,  temp1  )  ;
            
              temp1 = temp1.next ;
              temp = temp.next   ;
         }
    }
  
          return A  ;
}

    void  swap( ListNode head1 ,ListNode head2 )
{
    ListNode temp2 = head1 ; 
    head1  = head2 ;
    head2 = temp2  ;
    
}

}
.


#2

I think during the swap you didn’t link the swapped nodes with the linked list.


#3
use this code

`public class Solution {
public ListNode solve(ListNode A) {

if( A == null || A.next == null ) return A ;
ListNode temp1 = A ; 
ListNode temp = A ;

while( temp != null )
{
if( temp.val == 1 )
{
temp = temp.next ;
}
else
{
// swap( temp.val , temp1.val ) ;
int t=temp.val;
temp.val=temp1.val;
temp1.val=t;

          if(temp.val==1 || temp==temp1)temp = temp.next   ;
          temp1 = temp1.next ;
     }
}

      return A  ;
}

}`