用两个栈来实现队列 两个队列实现栈

用两个栈来实现队列

注意点:
当s2为空时 s1才能向s2倒数据,s1倒数据就要全部倒完

import java.util.Stack;
class newQueue{
	Stack<Integer> s1 = new Stack<Integer>();
	Stack<Integer> s2 = new Stack<Integer>();
	
	public void add(int value) {
		s1.push(value);
	}
	
	public int pop() {
		if (s1.isEmpty() && s2.isEmpty()) {
			return -1;
		} else {
			while (!s1.isEmpty() && s2.isEmpty()) {  
				s2.push(s1.pop());
			}
			return s2.pop();
		}
	}
	
	public int peek() {
		if (s1.isEmpty() && s2.isEmpty()) {
			return -1;
		} else {
			while (!s1.isEmpty()) {
				s2.push(s1.pop());
			}
			return s2.peek();
		}
	}
}

没错我就是灵魂画手!
在这里插入图片描述

两个队列实现栈

pop 两个队列 一个放数据一个空 当要弹出栈顶的时候 让这个队列中前几项放到空队列中 只留下需要弹出的数据 这个时候改变引用 help改成data
peek就是只返回给用户不弹出

public class TwoQueueStack {
	
	private Queue<Integer> data;
	private Queue<Integer> help;
	
	public TwoQueueStack() {
		data = new LinkedList<Integer>();
		help = new LinkedList<Integer>();
	}
	
	public void push(int value) {   //全部放到data队列
		data.add(value);
	}
	
	public int peek() {
		if (data.isEmpty()) {
			throw new RuntimeException("Stack is empty");
		}
		while (data.size() != 1) {           //不止一个数的时候放到help只留下最后一个数据
			help.add(data.poll());
		}
		int res = data.poll();
		help.add(res);
		swap();
		return res;
	}
	
	
	public int pop() {
		if (data.isEmpty()) {
			throw new RuntimeException("Stack is empty");
		}			
		while (data.size() > 1) {        //不止一个数的时候放到help
			help.add(data.poll());
		}
		int res = data.poll();
		swap();
		return res;
	}
		
	public void swap() {      //改变引用
		Queue<Integer> temp = help;
		help = data;
		data = temp;
	}
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值