232.用栈实现队列
class MyQueue {
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
public MyQueue() {
}
public void push(int x) {
stack1.push(x);
}
public int pop() {
int pop;
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
int pop1 = stack1.pop();
stack2.push(pop1);
}
pop = stack2.pop();
} else {
pop = stack2.pop();
}
return pop;
}
public int peek() {
int peek;
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
int pop1 = stack1.pop();
stack2.push(pop1);
}
peek = stack2.peek();
} else {
peek = stack2.peek();
}
return peek;
}
public boolean empty() {
return stack1.empty() && stack2.isEmpty() ? true : false;
}
}
225.用队列实现栈
class MyStack {
Deque<Integer> deque = new LinkedList();
public MyStack() {
}
public void push(int x) {
deque.addFirst(x);
}
public int pop() {
int pop = deque.pollFirst();
return pop;
}
public int top() {
int peekFirst = deque.peekFirst();
return peekFirst;
}
public boolean empty() {
return deque.isEmpty();
}
}