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.

Chapter 2 | Linked Lists<br />

How to Approach:<br />

Linked list questions are extremely common. These can range from simple (delete a node in<br />

a linked list) to much more challenging. Ei<strong>the</strong>r way, we advise you to be extremely comfortable<br />

with <strong>the</strong> easiest questions. Being able to easily manipulate a linked list in <strong>the</strong> simplest<br />

ways will make <strong>the</strong> tougher linked list questions much less tricky. With that said, we present<br />

some “must know” code about linked list manipulation. You should be able to easily write<br />

this code yourself prior to your interview.<br />

Creating a Linked List:<br />

NOTE: When you’re discussing a linked list in an interview, make sure to underst<strong>and</strong><br />

whe<strong>the</strong>r it is a single linked list or a doubly linked list.<br />

1 class Node {<br />

2 Node next = null;<br />

3 int data;<br />

4 public Node(int d) { data = d; }<br />

5 void appendToTail(int d) {<br />

6 Node end = new Node(d);<br />

7 Node n = this;<br />

8 while (n.next != null) { n = n.next; }<br />

9 n.next = end;<br />

10 }<br />

11 }<br />

Deleting a Node from a Singly Linked List<br />

1 Node deleteNode(Node head, int d) {<br />

2 Node n = head;<br />

3 if (n.data == d) {<br />

4 return head.next; /* moved head */<br />

5 }<br />

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

7 if (n.next.data == d) {<br />

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

9 return head; /* head didn’t change */<br />

10 }<br />

11 n = n.next;<br />

12 }<br />

13 }<br />

4 9<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!