1.利用两个栈实现一个队列
import java.util.Stack;
public class MyQueue {
/**
* 利用两个栈实现一个队列
* */
public static Stack<Integer> stack = new Stack<>();
public static Stack<Integer> tmpStack = new Stack<>();
// 将元素入列
public boolean add(Object obj){
if (offer(obj)) return true;
else throw new IllegalStateException("IllegalStateException");
}
// 在队列中add方法 其实上是调用了offer方法 有兴趣的读者可以查看源码实现
public boolean offer(Object obj){
try {
stack.push((Integer) obj);
return true;
}catch (Exception e){
return false;
}
}
//获取并移除栈顶元素
public Integer pop(){
while (!stack.isEmpty()){
tmpStack.push(stack.pop());
}
return tmpStack.pop();
}
//获取栈顶元素
public Integer peek(){
while (!stack.isEmpty()){
tmpStack.push(stack.pop());
}
return tmpStack.peek();
}
//判断栈是否为空
public boolean empty(){
return stack.isEmpty()&&tmpStack.isEmpty();
}
//获取元素个数
public int size(){
return stack.size()>tmpStack.size()?stack.size():tmpStack.size();
}
public static void main(String[] args) {
MyQueue myQueue = new MyQueue();
myQueue.add(1);
myQueue.add(2);
myQueue.add(3);
System.out.println(myQueue.peek());//1
System.out.println(myQueue.pop());//1
System.out.println(myQueue.pop());//2
System.out.println(myQueue.empty());//false
System.out.println(myQueue.size());//1
}
}
2.利用两个队列实现一个栈
import java.util.LinkedList;
import java.util.Queue;
/**
* 利用两个队列实现栈
* */
public class MyStack {
static Queue<Integer> queue = new LinkedList<>();
static Queue<Integer> tmpQueue = new LinkedList<>();
//获取栈顶元素
public Integer peek(){
if(queue==null||queue.size()==0){
while (!tmpQueue.isEmpty()){
queue.add(tmpQueue.poll());
}
}
int temp = 0;
while (!queue.isEmpty()){
temp = queue.poll();
tmpQueue.add(temp);
}
return temp;
}
//获取并移除栈顶元素
public Integer pop(){
if(queue==null||queue.size()==0) {
while (!tmpQueue.isEmpty()) {
queue.add(tmpQueue.poll());
}
}
while(!queue.isEmpty()){
if(queue.size()==1){
int res =queue.poll();
return res;
}else {
int temp = queue.poll();
tmpQueue.add(temp);
}
}
return 0;
}
//将元素入栈
public void push(Integer x){
queue.add(x);
}
//判断栈是否为空
public boolean empty(){
return queue.isEmpty()&&tmpQueue.isEmpty();
}
//获取元素个数
public int size(){
return queue.size()>tmpQueue.size()?queue.size():tmpQueue.size();
}
public static void main(String[] args) {
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.push(3);
System.out.println(myStack.peek());//3
System.out.println(myStack.pop());//3
System.out.println(myStack.pop());//2
System.out.println(myStack.empty());//false
System.out.println(myStack.size());//1
}
}