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.3 Implement an algorithm to delete a node in <strong>the</strong> middle of a single linked list, given<br />

only access to that node.<br />

EXAMPLE<br />

SOLUTION<br />

Input: <strong>the</strong> node ‘c’ from <strong>the</strong> linked list a->b->c->d->e<br />

Result: nothing is returned, but <strong>the</strong> new linked list looks like a->b->d->e<br />

pg 50<br />

The solution to this is to simply copy <strong>the</strong> data from <strong>the</strong> next node into this node <strong>and</strong> <strong>the</strong>n<br />

delete <strong>the</strong> next node.<br />

NOTE: This problem can not be solved if <strong>the</strong> node to be deleted is <strong>the</strong> last node<br />

in <strong>the</strong> linked list. That’s ok—your interviewer wants to see you point that out. You<br />

could consider marking it as dummy in that case. This is an issue you should discuss<br />

with your interviewer.<br />

1 public static boolean deleteNode(LinkedListNode n) {<br />

2 if (n == null || n.next == null) {<br />

3 return false; // Failure<br />

4 }<br />

5 LinkedListNode next = n.next;<br />

6 n.data = next.data;<br />

7 n.next = next.next;<br />

8 return true;<br />

9 }<br />

1 0 7<br />

<strong>Cracking</strong> <strong>the</strong> <strong>Coding</strong> <strong>Interview</strong> | Data Structures

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

Saved successfully!

Ooh no, something went wrong!