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.

Chapter 3 | Stacks <strong>and</strong> Queues<br />

How to Approach:<br />

Whe<strong>the</strong>r you are asked to implement a simple stack / queue, or you are asked to implement<br />

a modified version of one, you will have a big leg up on o<strong>the</strong>r c<strong>and</strong>idates if you can flawlessly<br />

work with stacks <strong>and</strong> queues. Practice makes perfect! Here is some skeleton code for a Stack<br />

<strong>and</strong> Queue class.<br />

Implementing a Stack<br />

1 class Stack {<br />

2 Node top;<br />

3 Node pop() {<br />

4 if (top != null) {<br />

5 Object item = top.data;<br />

6 top = top.next;<br />

7 return item;<br />

8 }<br />

9 return null;<br />

10 }<br />

11 void push(Object item) {<br />

12 Node t = new Node(item);<br />

13 t.next = top;<br />

14 top = t;<br />

15 }<br />

16 }<br />

Implementing a Queue<br />

1 class Queue {<br />

2 Node first, last;<br />

3 void enqueue(Object item) {<br />

4 if (!first) {<br />

5 back = new Node(item);<br />

6 first = back;<br />

7 } else {<br />

8 back.next = new Node(item);<br />

9 back = back.next;<br />

10 }<br />

11 }<br />

12 Node dequeue(Node n) {<br />

13 if (front != null) {<br />

14 Object item = front.data;<br />

15 front = front.next;<br />

16 return item;<br />

17 }<br />

18 return null;<br />

19 }<br />

20 }<br />

5 1<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!