栈转换为队列

栈转换为队列,第1张

栈:先进后出

队列:先进先出

栈转队列需要用到两个栈,先把需存入的元素都存到第一个栈中再存到第二个栈中就可以实现先进先出。

将两个栈分别命名为in和out,将A1,A2,A3按A1,A2,A3的顺序放入in中,在放入out中。最后拿出的顺序为A1,A2,A3,完成栈转队列先进先出的原则。

以下为代码实现:

import java.util.Stack;
public class one {
    public static void main(String[] args) {
        my queue =new my();
        queue.offer("A1");
        queue.offer("A2");
        queue.offer("A3");
        while(!queue.isEmpty()) {//遍历输出
            System.out.println(queue.poll());
        }
    }
}
class my{
    private Stack in = new Stack();//入队栈
    
    private Stack out = new Stack();//出队栈
    public boolean isEmpty() {             //判空
        
        return in.size() == 0 && out.size() == 0;
        
    }
    //入队
    public void offer(T e) {
        while(!out.isEmpty()) {
            in.push(out.pop());
        }
        in.push(e);
    }
    //出队
    public T poll() {
        while(!in.isEmpty()) {
            out.push(in.pop());
        }
        return out.pop();
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/916519.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-16
下一篇 2022-05-16

发表评论

登录后才能评论

评论列表(0条)

保存