class MyQueue {
/* M1
private Stack stack, stack2;
// Push element x to the back of queue.
public void push(int x) {
while ( !stack.isEmpty() )
{
stack2.push( stack1.pop() );
}
stack2.push(x);
while( !stack2.isEmpty() )
{
stack.push( stack2.pop() );
}
}
// Removes the element from in front of queue.
public void pop() {
stack.pop();
}
// Get the front element.
public int peek() {
stack.peek();
}
// Return whether the queue is empty.
public boolean empty() {
return stack.isEmpty();
}
*/
// Last Exceed input : empty if delcare this way: private Stack stack, stack2;
private Stack stack = new Stack<>();
private Stack stack2 = new Stack<>();
public void push ( int x)
{
while( !stack2.isEmpty() )
{
stack.push( stack2.pop() );
}
stack.push(x);
}
public void pop()
{
while ( !stack.isEmpty() )
{
stack2.push(stack.pop());
}
stack2.pop();
}
public int peek()
{
while ( !stack.isEmpty() )
{
stack2.push(stack.pop());
}
return stack2.peek();
}
public boolean empty()
{
while( !stack2.isEmpty() )
{
stack.push( stack2.pop() );
}
return stack.isEmpty();
}
}
Saturday, July 11, 2015
[Leetcode]07/09 [Data Structure]Implement Queue using Stacks
/*
M1:
two stacks
push O(n)
pop O(1)
peek O(1)
M2:
one stack
push O(n)
pop O(n)
peek O(n)
*/
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment