Skip to content

Commit a4ea05a

Browse files
author
freemanzhang
committed
refactor and use two stacks
1 parent b093cdc commit a4ea05a

File tree

1 file changed

+21
-15
lines changed

1 file changed

+21
-15
lines changed

src/stack/ImplementQueueUsingStacks.java

Lines changed: 21 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -16,38 +16,44 @@ You may assume that all operations are valid (for example, no pop or peek operat
1616

1717
public class ImplementQueueUsingStacks
1818
{
19-
Stack<Integer> queue = new Stack<>();
19+
Stack<Integer> inbox = new Stack<>();
20+
Stack<Integer> outbox = new Stack<>();
2021

2122
// Push element x to the back of queue.
2223
public void push( int x )
2324
{
24-
Stack<Integer> temp = new Stack<>();
25-
while ( !queue.empty() )
26-
{
27-
temp.push( queue.pop() );
28-
}
29-
queue.push( x );
30-
while ( !temp.empty() )
31-
{
32-
queue.push( temp.pop() );
33-
}
25+
inbox.push( x );
3426
}
3527

3628
// Removes the element from in front of queue.
37-
public void pop()
29+
public int pop()
3830
{
39-
queue.pop();
31+
if ( outbox.isEmpty() )
32+
{
33+
while ( !inbox.isEmpty() )
34+
{
35+
outbox.push( inbox.pop() );
36+
}
37+
}
38+
return outbox.pop();
4039
}
4140

4241
// Get the front element.
4342
public int peek()
4443
{
45-
return queue.peek();
44+
if ( outbox.isEmpty() )
45+
{
46+
while ( !inbox.isEmpty() )
47+
{
48+
outbox.push( inbox.pop() );
49+
}
50+
}
51+
return outbox.peek();
4652
}
4753

4854
// Return whether the queue is empty.
4955
public boolean empty()
5056
{
51-
return queue.empty();
57+
return inbox.isEmpty() && outbox.isEmpty();
5258
}
5359
}

0 commit comments

Comments
 (0)