Untitled

mail@pastecode.io avatar
unknown
java
2 months ago
1.2 kB
3
Indexable
Never
public class Solution {

  public ListNode reverse(ListNode head)
  {
    ListNode prev=null;
    ListNode curr=head;

    while(curr!=null){

      ListNode nextNode=curr.next;
      curr.next=prev;
      prev=curr;
      curr=nextNode;

      if(nextNode!=null)
      {
        nextNode=nextNode.next;
      }
    }

    return prev;
  }
	public ListNode addTwoNumbers(ListNode A, ListNode B) {
	    //You can code here

      ListNode r1=reverse(A);
      ListNode r2=reverse(B);

      ListNode ans=null;
      ListNode tempNode=null;
      int carry=0;

      while(r1!=null || r2!=null || carry!=0){

        int sum=carry;

        if(r1!=null)
        {
          sum+=r1.val;
          r1=r1.next;
        }

        if(r2!=null){
          sum+=r2.val;
          r2=r2.next;

        }

        int digit=sum%10;
        carry=sum/10;

        ListNode newNode = new ListNode(digit);

        if(ans==null){

          ans=tempNode=newNode;
        }
        else{

          tempNode.next=newNode;
          tempNode=tempNode.next;
        }


      }

      return reverse(ans);




      
	}
}
Leave a Comment