02-两个栈模拟一个队列
数据结构特点:
1.队列和栈数据结构底层都是线性表,实现上可以为数组或者链表
2.队列:先进先出(FIFO=first in first out),有队尾进队头出
3.栈:后进先出(LIFO=last in first out)
/**
* 2个栈模拟队列:
* 实现原理:存和取分别用一个栈,栈A负责存,栈B负责取;
* 如果这个栈B为空,则一次性把栈A中的元素全部弹栈,再入栈到栈B,再从栈B取;
* 这样2次弹栈到入栈,就把元素的顺序调整为符合队列的先进先出特点。
* 栈:LIFO(last in first out)
* 队列:FIFO(first in first out)
* @author lqs
*/
public class QueueImplByTwoStack {
Stack<Integer> stack1= new Stack<>();
Stack<Integer> stack2= new Stack<>();
public boolean offer(Integer o){
return stack1.push(o)!=null;
}
public Integer poll(){
if (stack2.empty()) {
while(!stack1.empty()){
stack2.push(stack1.pop());
}
}
if (!stack2.empty()) {
return stack2.pop();
}
return null;
}
@Override
public String toString() {
System.out.println("stack1="+stack1);
System.out.println("stack2="+stack2);
final StringBuffer sb = new StringBuffer();
sb.append("(");
if (!stack1.empty()) {
for (int i = stack1.size()-1; i >=0; i--) {
sb.append(stack1.get(i)+",");
}
}
if (!stack2.empty()) {
for(int j= 0; j<stack2.size();j++){
if (j!=stack2.size()-1) {
sb.append(stack2.get(j)+",");
}else{
sb.append(stack2.get(j));
}
}
}
sb.append(")");
return sb.toString();
}
public static void main(String[] args) {
QueueImplByTwoStack mockQueue = new QueueImplByTwoStack();
mockQueue.offer(1);
mockQueue.offer(2);
mockQueue.offer(3);
mockQueue.offer(4);
mockQueue.poll();
mockQueue.offer(5);
mockQueue.offer(6);
mockQueue.offer(7);
mockQueue.poll();
mockQueue.poll();
mockQueue.poll();
System.out.println(mockQueue.toString());
}
}
Last updated
Was this helpful?