class MyQueue {
private LinkedList<Integer> stack1;
private LinkedList<Integer> stack2;
/** Initialize your data structure here. */
public MyQueue() {
stack1 = new LinkedList<Integer>();
stack2 = new LinkedList<Integer>();
}
/** Push element x to the back of queue. */
public void push(int x) {
stack1.push(x);
}
private void trans (){
for (int i=stack1.size();i>0;i--){
stack2.push(stack1.pop());
}
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if (stack2.size()==0) trans();
return stack2.pop();
}
/** Get the front element. */
public int peek() {
if (stack2.size()==0) trans();
return stack2.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return stack1.size()==0 && stack2.size()==0;
}
}
用栈实现队列
最新推荐文章于 2023-06-13 22:01:40 发布
博客围绕用栈实现队列展开,虽无具体内容,但核心是利用栈这种数据结构来达成队列的功能,涉及数据结构的运用与转换,属于信息技术领域的数据结构相关知识。
4817

被折叠的 条评论
为什么被折叠?



