20190805:两个队列实现栈

本文介绍了一种使用两个队列实现栈数据结构的方法。通过在两个队列间转移元素,可以实现出栈和入栈操作,同时保持栈的特性。文章提供了详细的Java代码实现,包括构造器、入栈(push)、出栈(pop)、获取栈顶元素(top)和判断栈是否为空(empty)等核心功能。

两个队列实现栈的java实现

两个队列实现栈

力扣简单习题:在这里插入图片描述

大致思路

在这里插入图片描述

代码实现

package com.immunize.leetcode.implementQueue;

import java.util.LinkedList;

/**
 * 使用队列实现栈
 * 
 * @author Mr IMMUNIZE
 *
 */
class Queue2Stack {
	// 两个队列
	private LinkedList<Integer> queue1;
	private LinkedList<Integer> queue2;

	// 构造器初始化两个队列
	public Queue2Stack() {
		queue1 = new LinkedList<Integer>();
		queue2 = new LinkedList<Integer>();
	}

	// 入栈操作:找到非空栈,将元素放入非空栈
	public void push(int x) {
		if (queue1.isEmpty() && queue2.isEmpty()) {
			queue1.addLast(x);
		} else if (queue1.isEmpty()) {
			queue2.addLast(x);
		} else {
			queue1.addLast(x);
		}
	}

	// 出栈:将非空栈q1(q2)中的1-倒数第二个元素出栈,并且放入q2(q1),剩余的最后一个出队,即为出栈操作
	public int pop() {
		if (queue1.isEmpty()) {
			int len = queue2.size();
			for (int i = 0; i < len - 1; i++) {
				queue1.addLast(queue2.removeFirst());
			}
			return queue2.removeFirst();
		} else {
			int len = queue1.size();
			for (int i = 0; i < len - 1; i++) {
				queue2.addLast(queue1.removeFirst());
			}
			return queue1.removeFirst();
		}
	}

	// 非空队列中的最后一个元素即为栈顶元素,也就是最后一个进来的
	public int top() {
		if (queue1.isEmpty()) {
			return queue2.getLast();
		} else {
			return queue1.getLast();
		}
	}

	// 两个队列都空的时候,视为栈空
	public boolean empty() {
		return queue1.isEmpty() && queue2.isEmpty();
	}
}

-------------------------------------------------------------------------------------------
package com.immunize.leetcode.implementQueue;

/**
 * 测试
 * 
 * @author Mr IMMUNIZE
 *
 */
public class Queue2Stack_Test {

	public static void main(String[] args) {
		Queue2Stack q2s = new Queue2Stack();
		q2s.push(5);
		q2s.push(4);
		q2s.push(3);
		q2s.push(2);
		q2s.push(1);
		System.out.println(q2s.top());
		q2s.pop();
		System.out.println(q2s.top());
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IMMUNIZE

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值