Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Add Two Numbers saved in linked lists
//'main' method must be in a class 'Rextester'. //Compiler version 1.8.0_111 import java.util.*; import java.lang.*; class Rextester { public static void main(String args[]) { System.out.println("Hello, World!"); ListNode l1 = new ListNode(2); l1.next=new ListNode(4); l1.next.next = new ListNode(3); ListNode l2 = new ListNode(5); l2.next=new ListNode(6); l2.next.next = new ListNode(4); ListNode ans = addTwoNumbers(l1,l2); while(ans!=null){ System.out.println(ans.val+"->"); ans = ans.next; } } /* Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807. */ public static ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode p = l1,q=l2; ListNode ans = new ListNode(0); int carry=0; ListNode curr = ans; while(p!=null || q!=null){ int p1 = (p!=null?p.val:0); int q1 = (q!=null?q.val:0); int sum = p1+q1+carry; carry = sum/10; curr.next=new ListNode(sum%10); curr = curr.next; if(p!=null) p = p.next; if(q!=null) q = q.next; } if(carry>1) curr.next=new ListNode(carry); return ans.next; } } class ListNode { int val; ListNode next; ListNode(int x) { val = x; } }
run
|
edit
|
history
|
help
0
currency.java
extends
do while
sortArraymerge
Convert string array to lowercase.
Meena
pattern of the day (code formatting fixed)
binary
Basic tree implementation
Ip address