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 />

1 LinkedListNode FindBeginning(LinkedListNode head) {<br />

2 LinkedListNode n1 = head;<br />

3 LinkedListNode n2 = head;<br />

4<br />

5 // Find meeting point<br />

6 while (n2.next != null) {<br />

7 n1 = n1.next;<br />

8 n2 = n2.next.next;<br />

9 if (n1 == n2) {<br />

10 break;<br />

11 }<br />

12 }<br />

13<br />

14 // Error check - <strong>the</strong>re is no meeting point, <strong>and</strong> <strong>the</strong>refore no loop<br />

15 if (n2.next == null) {<br />

16 return null;<br />

17 }<br />

18<br />

19 /* Move n1 to Head. Keep n2 at Meeting Point. Each are k steps<br />

20 /* from <strong>the</strong> Loop Start. If <strong>the</strong>y move at <strong>the</strong> same pace, <strong>the</strong>y must<br />

21 * meet at Loop Start. */<br />

22 n1 = head;<br />

23 while (n1 != n2) {<br />

24 n1 = n1.next;<br />

25 n2 = n2.next;<br />

26 }<br />

27 // Now n2 points to <strong>the</strong> start of <strong>the</strong> loop.<br />

28 return n2;<br />

29 }<br />

n1 <strong>and</strong> n2 will meet here, 3<br />

nodes from start of loop<br />

CareerCup.com<br />

1 1 0

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

Saved successfully!

Ooh no, something went wrong!