用两个栈实现队列(Java实现)

用两个栈实现队列


import java.util.Stack;

public class E09CreateQueueByStack<T> {
    //用两个栈实现队列,采用泛型

    private Stack<T> stack1 = new Stack<>();
    private Stack<T> stack2 = new Stack<>();

    public void addTail(T element){
        //始终在栈1中添加元素
        stack1.push(element);
    }

    public T deleteHead(){
        //始终在栈2中删除元素,栈2为空则尝试从栈1中弹出元素到栈2中
        if (stack2.empty()){
            while(!stack1.empty())
                stack2.push(stack1.pop());
            //栈1也为空则抛出异常
            if (stack2.empty())
                throw new IllegalArgumentException("Empty Queue");
            else
                return stack2.pop();
        }
        else
            return stack2.pop();
    }

    //测试用例
    public static void main(String[] args){
        E09CreateQueueByStack<Integer> queue = new E09CreateQueueByStack<>();
        //System.out.print(queue.deleteHead());
        for (int i = 0; i < 10; i++)
            queue.addTail(i);
        System.out.print(queue.deleteHead());
    }
}

用两个队列实现栈

import java.util.LinkedList;
import java.util.Queue;

public class E09CreateStackByQueue<T> {
    private Queue<T> queue1 = new LinkedList<>();
    private Queue<T> queue2 = new LinkedList<>();

    public T deleteTail(){
        //在不为空的队列中,将元素放入另一队列中,删除最后一个元素
        if(!queue1.isEmpty()){
            while(queue1.size() > 1)
                queue2.offer(queue1.poll());
            return queue1.poll();
        }
        if(!queue2.isEmpty()){
            while(queue2.size() > 1)
                queue1.offer(queue2.poll());
            return queue2.poll();
        }
        throw new IllegalArgumentException("Empty Stack");
    }

    public void addTail(T element){
        if (!queue1.isEmpty())
            queue1.offer(element);
        else if (!queue2.isEmpty())
            queue2.offer(element);
        else
            queue1.offer(element);
    }

    //测试用例
    public static void main(String[] args){
        E09CreateStackByQueue<Integer> stack = new E09CreateStackByQueue<>();
        stack.addTail(1);
        stack.addTail(2);
        stack.addTail(3);
        System.out.println(stack.deleteTail());
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值