- 题目一: 用两个栈实现一个队列
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
import java.util.Stack;
public class MyTest {
public static void main(String[] args) {
MyQueue myQueue = new MyQueue();
myQueue.push(1);
myQueue.push(2);
myQueue.push(3);
System.out.println(myQueue.pop());
System.out.println(myQueue.pop());
myQueue.push(4);
System.out.println(myQueue.pop());
System.out.println(myQueue.pop());
}
}
class MyQueue {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int data) {
stack1.push(data);
}
public int pop() {
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
int temp = stack1.pop();
stack2.push(temp);
}
}
return stack2.pop();
}
}
- 题目二: 用两个队列实现一个栈
用两个队列来实现一个栈,完成栈的Push和Pop操作。 栈中的元素为int类型。
import java.util.Queue;
import java.util.LinkedList;
public class MyTest {
public static void main(String[] args) {
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.push(3);
System.out.println(myStack.pop());
System.out.println(myStack.pop());
myStack.push(4);
System.out.println(myStack.pop());
System.out.println(myStack.pop());
System.out.println(myStack.pop());
}
}
class MyStack{
Queue<Integer> queue1 = new LinkedList<>();
Queue<Integer> queue2 = new LinkedList<>();
public void push(int data){
if(!queue1.isEmpty()){
queue1.offer(data);
}else{
queue2.offer(data);
}
}
public Integer pop(){
if(!queue1.isEmpty()){
while(queue1.size() > 1){
queue2.offer(queue1.poll());
}
return queue1.poll();
}else if(!queue2.isEmpty()){
while(queue2.size() > 1){
queue1.offer(queue2.poll());
}
return queue2.poll();
}else{
return null;
}
}
}