leetcode-232
Implement Queue using Stacks
Implement the following operations of a queue using stacks.
- push(x) -- Push element x to the back of queue.
- pop() -- Removes the element from in front of queue.
- peek() -- Get the front element.
- empty() -- Return whether the queue is empty.
题目的大概意思就是让我们用栈实现队列的相关功能。Stack是java里面已经写好的栈类可以直接使用。
java代码:
public class MyQueue{
Stack<Integer> queue=new Stack<Integer>();
public void push(int x){
Stack<Integer> temp=new Stack<Integer>();
while(!queue.empty()){
temp.push(queue.pop());
}
queue.push(x);
while(!temp.empty()){
queue.push(temp.pop());
}
}
public int pop(){
return queue.pop();
}
public int peek(){
return queue.peek();
}
public boolean empty(){
return queue.empty();
}
}
浙公网安备 33010602011771号