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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

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

2.2 Implement an algorithm to find <strong>the</strong> nth to last element of a singly linked list.<br />

SOLUTION<br />

pg 50<br />

Note: This problem screams recursion, but we’ll do it a different way because it’s<br />

trickier. In a question like this, expect follow up questions about <strong>the</strong> advantages<br />

of recursion vs iteration.<br />

Assumption: The minimum number of nodes in list is n.<br />

Algorithm:<br />

1. Create two pointers, p1 <strong>and</strong> p2, that point to <strong>the</strong> beginning of <strong>the</strong> node.<br />

2. Increment p2 by n-1 positions, to make it point to <strong>the</strong> nth node from <strong>the</strong> beginning (to<br />

make <strong>the</strong> distance of n between p1 <strong>and</strong> p2).<br />

3. Check for p2->next == null if yes return value of p1, o<strong>the</strong>rwise increment p1 <strong>and</strong> p2.<br />

If next of p2 is null it means p1 points to <strong>the</strong> nth node from <strong>the</strong> last as <strong>the</strong> distance<br />

between <strong>the</strong> two is n.<br />

4. Repeat Step 3.<br />

1 LinkedListNode nthToLast(LinkedListNode head, int n) {<br />

2 if (head == null || n < 1) {<br />

3 return null;<br />

4 }<br />

5 LinkedListNode p1 = head;<br />

6 LinkedListNode p2 = head;<br />

7 for (int j = 0; j < n - 1; ++j) { // skip n-1 steps ahead<br />

8 if (p2 == null) {<br />

9 return null; // not found since list size < n<br />

10 }<br />

11 p2 = p2.next;<br />

12 }<br />

13 while (p2.next != null) {<br />

14 p1 = p1.next;<br />

15 p2 = p2.next;<br />

16 }<br />

17 return p1;<br />

18 }<br />

CareerCup.com<br />

1 0 6

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

Saved successfully!

Ooh no, something went wrong!