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 3 | Stacks <strong>and</strong> Queues<br />

3.5 Implement a MyQueue class which implements a queue using two stacks.<br />

SOLUTION<br />

pg 52<br />

Since <strong>the</strong> major difference between a queue <strong>and</strong> a stack is <strong>the</strong> order (first-in-first-out vs. lastin-first-out),<br />

we know that we need to modify peek() <strong>and</strong> pop() to go in reverse order. We<br />

can use our second stack to reverse <strong>the</strong> order of <strong>the</strong> elements (by popping s1 <strong>and</strong> pushing<br />

<strong>the</strong> elements on to s2). In such an implementation, on each peek() <strong>and</strong> pop() operation, we<br />

would pop everything from s1 onto s2, perform <strong>the</strong> peek / pop operation, <strong>and</strong> <strong>the</strong>n push<br />

everything back.<br />

This will work, but if two pop / peeks are performed back-to-back, we’re needlessly moving<br />

elements. We can implement a “lazy” approach where we let <strong>the</strong> elements sit in s2.<br />

s1 will thus be ordered with <strong>the</strong> newest elements on <strong>the</strong> top, while s2 will have <strong>the</strong> oldest<br />

elements on <strong>the</strong> top. We push <strong>the</strong> new elements onto s1, <strong>and</strong> peek <strong>and</strong> pop from s2. When<br />

s2 is empty, we’ll transfer all <strong>the</strong> elements from s1 onto s2, in reverse order.<br />

1 public class MyQueue {<br />

2 Stack s1, s2;<br />

3 public MyQueue() {<br />

4 s1 = new Stack();<br />

5 s2 = new Stack();<br />

6 }<br />

7<br />

8 public int size() {<br />

9 return s1.size() + s2.size();<br />

10 }<br />

11<br />

12 public void add(T value) {<br />

13 s1.push(value);<br />

14 }<br />

15<br />

16 public T peek() {<br />

17 if (!s2.empty()) return s2.peek();<br />

18 while (!s1.empty()) s2.push(s1.pop());<br />

19 return s2.peek();<br />

20 }<br />

21<br />

22 public T remove() {<br />

23 if (!s2.empty()) return s2.pop();<br />

24 while (!s1.empty()) s2.push(s1.pop());<br />

25 return s2.pop();<br />

26 }<br />

27 }<br />

CareerCup.com<br />

1 2 0

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

Saved successfully!

Ooh no, something went wrong!