Java Solution easy to understand


  • 0
    M

    /**

    • 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) {
      Integer carry = 0;
      if (l1 == null)
      return l2;
      if (l2 == null)
      return l1;
      ListNode head = l1;
      ListNode preL1 = null;
      while(l1 != null || l2 != null) {
      if(l1 == null) {
      l1 = new ListNode(0);
      preL1.next = l1;
      }
      if(l2 == null) {
      l2= new ListNode(0);
      }
      l1.val = l1.val + l2.val + carry;
      if(l1.val > 9) {
      l1.val = l1.val - 10;
      carry = 1;
      } else {
      carry = 0;
      }
      preL1 = l1;
      l1 = l1.next;
      l2 = l2.next;
      }
      if(carry == 1) {
      preL1.next = new ListNode(1);
      }
      return head;
      }
      }
      '''

  • 0
    M

    @messio said in Java Solution easy to understand:

    /**

    • 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) {
      Integer carry = 0;
      if (l1 == null)
      return l2;
      if (l2 == null)
      return l1;
      ListNode head = l1;
      ListNode preL1 = null;
      while(l1 != null || l2 != null) {
      if(l1 == null) {
      l1 = new ListNode(0);
      preL1.next = l1;
      }
      if(l2 == null) {
      l2= new ListNode(0);
      }
      l1.val = l1.val + l2.val + carry;
      if(l1.val > 9) {
      l1.val = l1.val - 10;
      carry = 1;
      } else {
      carry = 0;
      }
      preL1 = l1;
      l1 = l1.next;
      l2 = l2.next;
      }
      if(carry == 1) {
      preL1.next = new ListNode(1);
      }
      return head;
      }
      }

Log in to reply
 

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