implement a queue using stack

本文介绍了一种使用两个栈来实现队列的方法。通过将一个栈用于入队操作,另一个栈用于出队操作,可以有效地模拟队列的先进先出特性。文章详细解释了入队和出队的过程,并指出该实现方式与使用队列实现栈类似。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//implement a queue using stack

public class Solution {
    Stack<Integer>  stack1 = new Stack<Integer>();
    Stack<Integer>  stack2 = new Stack<Integer>();

	//pop: dequeue in stack1
	public void dequeue() {
        if (stack1.peek() == null) {
        	System.out.println("The queue is empty!");
        } else {
        	int pop = stack1.pop();
        	return pop;
        }
	}
    //1.pop all the items from stack1 to stack2
    //2.push the new item in stack1
    //3.pop all the items in stack2 to stack1
	public void enqueue(int data) {
		if (stack.peek() == null) {
			stack1.push(data);
		} else {
			for (int i = stack1.size(); i > 0; i--) {
				stack2.push(stack1.pop());
			} 
			stack1.push(data);

			for (int j = stack2.size(); j > 0; j--) {
				stack1.push(stack2.pop());
			}
		}

	}

}


The solution is similar to implement a stack using queue.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值