My java solution without reversing the LinkedList


  • 0

    '''
    /**

    • Definition for singly-linked list.

    • public class ListNode {

    • int val;
      
    • ListNode next;
      
    • ListNode(int x) { val = x; }
      
    • }
      */
      public class Solution {
      public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
      ListNode temp1=l1; ListNode temp2=l2;
      if(l1==null && l2==null){
      return null;
      }
      if(l1!=null && l2==null){
      return null;
      }
      if(l1==null && l2!=null){
      return null;
      }
      int carry=0;

       ListNode head = new ListNode((temp1.val+temp2.val+carry)%10);
       ListNode limp = head;
       carry=(temp1.val+temp2.val+carry)/10;
       temp1=temp1.next;
       temp2=temp2.next;
       
       while(temp1!=null && temp2!=null){
           if(carry!=0 && temp1.next==null && temp2.next==null){
               ListNode carryNode = new ListNode(carry);
               head.next=carryNode;
           }
           ListNode node = new ListNode((temp1.val+temp2.val+carry)%10);
           carry=(temp1.val+temp2.val+carry)/10;
           head.next=node;
           head=head.next;
           temp1=temp1.next;
           temp2=temp2.next;
       }
           while(temp1!=null){
               ListNode node = new ListNode((temp1.val+carry)%10);
               carry=(temp1.val+carry)/10;
               head.next=node;
               head=head.next;
               temp1=temp1.next;
           }
           while(temp2!=null){
               ListNode node = new ListNode((temp2.val+carry)%10);
               carry=(temp2.val+carry)/10;
               head.next=node;
               head=head.next;
               temp2=temp2.next;
           }
       if(carry!=0 && temp1==null && temp2==null){
               ListNode carryNode = new ListNode(carry);
               head.next=carryNode;
               head=head.next;
       }
       return limp;
      

      }
      }
      '''


Log in to reply
 

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