【数据结构算法】如何使用两个栈实现队列

首先初始化两个栈S1,S2。

入队算法:直接将所有元素压入其中一个栈(S1),over。

出队算法:若S2不为空,S2执行出栈操作,返回栈顶元素。

                  若S2为空,将S1中的所有元素压入S2,并返回S2的栈顶元素。

下面代码:

package MyCollection;

public class Test01 {
	/**
	 * 用两个栈实现队列
	 * 
	 * @author ZJ
	 *
	 */
	class QueueWithTowStack {
		MyStack stack1;
		MyStack stack2;

		public QueueWithTowStack() {
			stack1 = new MyStack();
			stack2 = new MyStack();
		}

		public boolean isEmpty() {// 判断Stack2是否为空,若为空,将stack1压入stack2同时返回true或false.
			if (stack2.isEmpty()) {
				while (!stack1.isEmpty()) {
					stack2.push(stack1.pop());
				}
			}
			return stack2.isEmpty();
		}

		public void enQueue(Object obj) {
			stack1.push(obj);
		}

		public Object deQueue() {
			if (!stack2.isEmpty()) {
				return stack2.pop();
			} else {
				while (!stack1.isEmpty()) {
					stack2.push(stack1.pop());
				}
			}
			return stack2.pop();
		}

	}
public static void main(String[] args) { 
    String[] s1={"111","2222","333"};       
    Test01 t1 = new Test01();
    QueueWithTowStack queueWithTowStack=t1.new QueueWithTowStack();
    for (int i = 0; i < s1.length; i++) {
    queueWithTowStack.enQueue(s1[i]);
        }
    queueWithTowStack.isEmpty();
    System.out.println(queueWithTowStack.deQueue());
    System.out.println(queueWithTowStack.deQueue());
    System.out.println(queueWithTowStack.deQueue());
}

 

111
2222
333

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值