Memory Limit Exceed - Java


  • 0
    K

    Can someone help me understand why am I getting error of : Memory Limit Exceed.

    Here is my code:

    /**

    • 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 head = null;
      ListNode current = null;
      int carry = 0;
      int first=0, second=0, value=0, add=0;

       while(l1 != null || l2 != null){
           
           if(l1 != null)
               first = l1.val;
           if(l2 != null)
               second = l2.val;
           add = first + second + carry;
           value = add > 0 ? 0 : add;
           carry = add > 0 ? 1 : 0;
           
           if(head == null){
               head = new ListNode(value);
               current = head;
           } else if(current.next == null){
               current.next = new ListNode(value);
               current = current.next;
           }
           
       }
       return head;
      

      }
      }


Log in to reply
 

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