Add two numbers represented by linked lists (each node contains a digit) ListNode AddTwoNumbers(ListNode l1, ListNode l2) { ListNode dummy = new ListNode(0); ListNode curr = dummy; int carry = 0; while (l1 != null || l2 != null || carry != 0) { int x = (l1 != null) ?
Short answer: l1.val : 0; int y = (l2 != null) ? l2.val : 0; int sum = x + y + carry; carry = sum / 10; curr.next = new ListNode(sum % 10); curr = curr.next; if (l1 != null) l1 = l1.next; if (l2 != null) l2 = l2.next; Follow on: return dummy.next; Explanation: Add digit by digit with carry, creating new nodes for the result. l1.val : 0; int y = (l2 != null) ? l2.val :… 0;… int sum = x + y + carry; carry = sum / 10; curr.next =…
Explain a bit more
new ListNode(sum % 10); curr = curr.next; if (l1 != null) l1 = l1.next; if (l2 != null) l2 = l2.next; Follow on: return dummy.next; Explanation: Add digit by digit with carry, creating new nodes for the result.
Real-world example (ShopNest)
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).
Say this in the interview
- Define — one clear sentence (the short answer above).
- Example — relate it to a project like ShopNest or your real work.
- Trade-off — when you would not use it.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png