剑指offer系列-用两个队列实现栈

本人对java语言更熟悉,所以剑指offer代码都是通过Java实现,且涉及的核心代码全部通过牛客网的测试用例检查,感谢牛客网为我检验程序提供了极大帮助!main函数是为了在自己运行程序时,运行结果更直观化。

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

/**
 * @author xhl 用两个队列实现栈 获得queue对象时,要明确,java.util.Queue是接口,
 *         要找到该接口的的实现类,这里用LinkedList类,LinkedList实现了 Deque接口,Deque又实现了Queue接口;
 *         该程序的思想就是两个队列,一个盛放元素,一个为空,空队列作为有元素的队列的
 *         中转容器,所以在实现push时先判断哪个不空再offer;在实现pop时,先把有元素的
 *         队列的前n-1个元素pull再offer到空队列中,再pull出最后进去的第n个元素
 * 
 */
public class offerT7_2 {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		stack o = new stack();
		o.push(1);
		o.push(2);
		o.push(3);
		ArrayList<Integer> list = new ArrayList<Integer>();
		list.add(o.pop());
		list.add(o.pop());
		list.add(o.pop());
		// list.add(o.pop());
		for (int i : list) {
			System.out.println(i);
		}
	}

}

class stack {
	private Queue<Integer> queue1 = new LinkedList<Integer>();
	private Queue<Integer> queue2 = new LinkedList<Integer>();

	int pop() {
		Integer popnode = null;
		// Queue<Integer> use=null;
		if (queue1.isEmpty() == true) {
			if (queue2.isEmpty() != true) {
				while (queue2.size() > 1)
					queue1.offer(queue2.poll());
				popnode = queue2.poll();
			}
		} else if (queue2.isEmpty() == true) {
			while (queue1.size() > 1)
				queue2.offer(queue1.poll());
			popnode = queue1.poll();
		}
		return popnode;
	}

	void push(int pushnode) {
		if (queue1.isEmpty() == true) {
			queue2.offer(pushnode);
		} else if (queue2.isEmpty() == true)
			queue1.offer(pushnode);
		else
			System.out.print(false);

	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值