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.6 Write a program to sort a stack in ascending order. You should not make any assumptions<br />

about how <strong>the</strong> stack is implemented. The following are <strong>the</strong> only functions that<br />

should be used to write this program: push | pop | peek | isEmpty.<br />

SOLUTION<br />

pg 52<br />

Sorting can be performed with one more stack. The idea is to pull an item from <strong>the</strong> original<br />

stack <strong>and</strong> push it on <strong>the</strong> o<strong>the</strong>r stack. If pushing this item would violate <strong>the</strong> sort order of <strong>the</strong><br />

new stack, we need to remove enough items from it so that it’s possible to push <strong>the</strong> new<br />

item. Since <strong>the</strong> items we removed are on <strong>the</strong> original stack, we’re back where we started. The<br />

algorithm is O(N^2) <strong>and</strong> appears below.<br />

1 public static Stack sort(Stack s) {<br />

2 Stack r = new Stack();<br />

3 while(!s.isEmpty()) {<br />

4 int tmp = s.pop();<br />

5 while(!r.isEmpty() && r.peek() > tmp) {<br />

6 s.push(r.pop());<br />

7 }<br />

8 r.push(tmp);<br />

9 }<br />

10 return r;<br />

11 }<br />

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