27.10.2014 Views

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Solutions</strong> to Chapter 2 | Linked Lists<br />

2.4 You have two numbers represented by a linked list, where each node contains a single<br />

digit. The digits are stored in reverse order, such that <strong>the</strong> 1’s digit is at <strong>the</strong> head of<br />

<strong>the</strong> list. Write a function that adds <strong>the</strong> two numbers <strong>and</strong> returns <strong>the</strong> sum as a linked<br />

list.<br />

EXAMPLE<br />

SOLUTION<br />

Input: (3 -> 1 -> 5), (5 -> 9 -> 2)<br />

Output: 8 -> 0 -> 8<br />

pg 50<br />

We can implement this recursively by adding node by node, just as we would digit by digit.<br />

1. result.data = (node1 + node2 + any earlier carry) % 10<br />

2. if node1 + node2 > 10, <strong>the</strong>n carry a 1 to <strong>the</strong> next addition.<br />

3. add <strong>the</strong> tails of <strong>the</strong> two nodes, passing along <strong>the</strong> carry.<br />

1 LinkedListNode addLists(LinkedListNode l1, LinkedListNode l2,<br />

2 int carry) {<br />

3 if (l1 == null && l2 == null) {<br />

4 return null;<br />

5 }<br />

6 LinkedListNode result = new LinkedListNode(carry, null, null);<br />

7 int value = carry;<br />

8 if (l1 != null) {<br />

9 value += l1.data;<br />

10 }<br />

11 if (l2 != null) {<br />

12 value += l2.data;<br />

13 }<br />

14 result.data = value % 10;<br />

15 LinkedListNode more = addLists(l1 == null ? null : l1.next,<br />

16 l2 == null ? null : l2.next,<br />

17 value > 10 ? 1 : 1);<br />

18 result.setNext(more);<br />

19 return result;<br />

20 }<br />

CareerCup.com<br />

1 0 8

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!