很抱歉,您没有提供需要改写的句子。请提供您希望改写的句子,我将为您改写为一个长尾词的。
- 内容介绍
- 文章标签
- 相关推荐
本文共计295个文字,预计阅读时间需要2分钟。
题目:实现一个MyQueue类,该类使用两个栈来实现一个队列。示例:javaMyQueue queue=new MyQueue();queue.push(1);queue.push(2);System.out.println(queue.peek()); // 返回 1System.out.println(queue.pop()); // 返回 1System.out.println(queue.empty()); // 返回 false代码实现:javaclass MyQueue { private Stack stackIn; private Stack stackOut;
public MyQueue() { stackIn=new Stack(); stackOut=new Stack(); }
public void push(int value) { stackIn.push(value); }
public int peek() { transfer(); return stackOut.peek(); }
public int pop() { transfer(); return stackOut.pop(); }
public boolean empty() { return stackIn.isEmpty() && stackOut.isEmpty(); }
private void transfer() { if (stackOut.isEmpty()) { while (!stackIn.isEmpty()) { stackOut.push(stackIn.pop()); } } }}
题目:
实现一个MyQueue类,该类用两个栈来实现一个队列。
示例:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
代码实现:
class MyQueue { Deque<Integer> inStack; Deque<Integer> outStack; public MyQueue() { inStack = new ArrayDeque<Integer>(); outStack = new ArrayDeque<Integer>(); } public void push(int x) { inStack.push(x); } public int pop() { if (outStack.isEmpty()) { in2out(); } return outStack.pop(); } public int peek() { if (outStack.isEmpty()) { in2out(); } return outStack.peek(); } public boolean empty() { return inStack.isEmpty() && outStack.isEmpty(); } private void in2out() { while (!inStack.isEmpty()) { outStack.push(inStack.pop()); } }}本文共计295个文字,预计阅读时间需要2分钟。
题目:实现一个MyQueue类,该类使用两个栈来实现一个队列。示例:javaMyQueue queue=new MyQueue();queue.push(1);queue.push(2);System.out.println(queue.peek()); // 返回 1System.out.println(queue.pop()); // 返回 1System.out.println(queue.empty()); // 返回 false代码实现:javaclass MyQueue { private Stack stackIn; private Stack stackOut;
public MyQueue() { stackIn=new Stack(); stackOut=new Stack(); }
public void push(int value) { stackIn.push(value); }
public int peek() { transfer(); return stackOut.peek(); }
public int pop() { transfer(); return stackOut.pop(); }
public boolean empty() { return stackIn.isEmpty() && stackOut.isEmpty(); }
private void transfer() { if (stackOut.isEmpty()) { while (!stackIn.isEmpty()) { stackOut.push(stackIn.pop()); } } }}
题目:
实现一个MyQueue类,该类用两个栈来实现一个队列。
示例:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
代码实现:
class MyQueue { Deque<Integer> inStack; Deque<Integer> outStack; public MyQueue() { inStack = new ArrayDeque<Integer>(); outStack = new ArrayDeque<Integer>(); } public void push(int x) { inStack.push(x); } public int pop() { if (outStack.isEmpty()) { in2out(); } return outStack.pop(); } public int peek() { if (outStack.isEmpty()) { in2out(); } return outStack.peek(); } public boolean empty() { return inStack.isEmpty() && outStack.isEmpty(); } private void in2out() { while (!inStack.isEmpty()) { outStack.push(inStack.pop()); } }}
