leetcode 232 栈实现队列
class MyQueue {
private Stack stack1;
private Stack stack2;
private int size;
public MyQueue() {
stack1 = new Stack();
stack2 = new Stack();
}
public void push(int x) {
stack1.push(x);
}
public int pop() {
if(stack2.isEmpty()) {
int tmp = stack1.size();
for (int i = 0; i < tmp; i++) {
stack2.push(stack1.pop());
}
}
return (int)stack2.pop();
}
public int peek() {
if(stack2.isEmpty()) {
int tmp = stack1.size();
for (int i = 0; i < tmp; i++) {
stack2.push(stack1.pop());
}
}
return (int)stack2.peek();
}
public boolean empty() {
if(stack2.isEmpty()){
int tmp = stack1.size();
for (int i = 0; i < tmp; i++) {
stack2.push(stack1.pop());
}
}
return stack2.isEmpty();
}
}
leetcoce 225 队列实现栈
class MyStack {
/*private Queue que1;
private Queue que2;
public MyStack() {
que1= new LinkedList();
que2= new LinkedList();
}
public void push(int x) {
que1.add(x);
}
public int pop() {
int tmp = que1.size();
for(int i=0;i< tmp-1;i++){
que2.add(que1.poll());
}
int result = (int) que1.poll();
int tmp2= que2.size();
for(int j=0;j< tmp2;j++){
que1.add(que2.poll());
}
return result;
}
public int top() {
int tmp = que1.size();
for(int i=0;i< tmp-1;i++){
que2.add(que1.poll());
}
int result = (int) que1.poll();
int tmp2= que2.size();
for(int j=0;j< tmp2;j++){
que1.add(que2.poll());
}
que1.add(result);
return result;
}
public boolean empty() {
return que1.isEmpty();
}*/
// 一个队列也可以实现
private Queue<Integer> que1;
public MyStack() {
que1= new LinkedList();
}
public void push(int x) {
que1.offer(x);
int tmp = que1.size();
for(int i=0;i< tmp-1;i++){
que1.offer(que1.poll());
}
}
public int pop() {
return que1.poll();
}
public int top() {
return que1.peek();
}
public boolean empty() {
return que1.isEmpty();
}
}