It works in Editor here on leetCode submitting or running the solutions gives runtime error


  • 0
    S
    public class Solution {
      public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode result = null;
            ListNode rootOfResult = null;
            boolean hasCarryOver = false;
            System.out.println("resultant list=");
            while(l1!=null && l2 != null){
                int resultVal = l1.getVal() + l2.getVal();
                if(hasCarryOver && resultVal <8){
                    resultVal = resultVal +1;
                }
                if(resultVal >= 10) {
                    resultVal = resultVal-10; //get SingleDigit only
                    hasCarryOver = true;
                }
                ListNode newNode = new ListNode(resultVal);
                System.out.print(newNode.getVal() + "->");
                newNode.setNext(null);
                if(result == null){
                    result = newNode;
                    rootOfResult = result;// root node of resultant list;
                } else {
                    result.setNext(newNode);
                    result = result.getNext();
                }
                //increment
                l1 = l1.getNext();
                l2=l2.getNext();
            }
            return rootOfResult;
        }
    }
    class ListNode {
         int val;
         ListNode next;
        ListNode(int x) { val = x; }
        
        public int getVal(){
            return val;
        }
        public void setNext(ListNode next){
            this.next = next;
        }
        public ListNode getNext(){
            return next;
        }
     }

Log in to reply
 

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