栈模拟队列
思路:两个栈操作
从一个栈中push 从另外一个栈中pop
import java.util.Stack;
/**
* @author yinglala
* 栈模拟队列
* 思路:两个栈操作
* 从一个栈中push 从另外一个栈中pop
*/
public class Stack2Queue {
private Stack stack1 = new Stack();
private Stack stack2 = new Stack();
//synchronized保证线程同步安全
public synchronized void put(Object o){
stack1.push(o);
}
public synchronized Object pop(){
if(stack2.isEmpty() && stack1.isEmpty()){
return null;
}
if(stack2.isEmpty()){
while (!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
public static void main(String[] args) {
Stack2Queue s2q = new Stack2Queue();
s2q.put(1);//第一元素
s2q.put(2);//第二元素
s2q.put(3);//第三元素
System.out.println("栈模拟队列后head的数据"+s2q.pop());
System.out.println("栈模拟队列后第二个数据"+s2q.pop());
System.out.println("栈模拟队列后第三个数据"+s2q.pop());
}
}
队列模拟栈
思路:用两个队列 queue1 queue2
* push:往一个队列queue1中add
* pop:也在同一个队列queue1中remove最后一条数据,其他的要放在queue2中暂存,当queue1中没有数据把queue2的数据放回来
import java.util.LinkedList;
import java.util.Queue;
/**
* @author yinglala
* 队列模拟栈
* 思路:用两个队列 queue1 queue2
* push:往一个队列queue1中add
* pop:也在同一个队列queue1中remove最后一条数据,其他的要放在queue2中暂存,当queue1中没有数据把queue2的数据放回来
*/
public class Queue2Stack {
private Queue queue1 = new LinkedList();
private Queue queue2 = new LinkedList();
public synchronized void push(Object o){
queue1.add(o);
}
public synchronized Object pop(){
if(queue1.isEmpty() && queue2.isEmpty()){
return null;
}
if(queue1.isEmpty()){
while (!queue2.isEmpty()){
queue1.add(queue2.remove());
}
}
while (queue1.size()>1){
queue2.add(queue1.remove());
}
return queue1.remove();
}
public static void main(String[] args) {
Queue2Stack q2s = new Queue2Stack();
q2s.push(1);//第一元素
q2s.push(2);//第二元素
q2s.push(3);//第三元素
System.out.println("栈模拟队列后head的数据"+q2s.pop());
System.out.println("栈模拟队列后第二个数据"+q2s.pop());
System.out.println("栈模拟队列后第三个数据"+q2s.pop());
System.out.println("栈模拟队列后第四个数据"+q2s.pop());
}
}
参考链接:https://www.cnblogs.com/qichunlin/p/9590332.html