队列结构实现栈结构,栈结构实现队列结构

这篇博客探讨了如何使用队列结构实现栈功能,以及如何使用栈结构实现队列功能。通过两个队列来模拟栈操作,push时直接放入队列1,pop时将队列1除最后一个元素外的所有元素转移至队列2,然后弹出队列1的最后一个元素。同样,用两个栈来模拟队列,push操作时元素进入栈1,poll操作时将栈1元素转移至栈2再进行poll。代码实现给出了详细过程。
摘要由CSDN通过智能技术生成

用队列实现栈结构,可以用两个队列来实现。一个用来插入数据,一个用来辅助实现pop和push。push时直接把数放在第一个队列中,pop时,先把队列1里除了最后一个push进去的数全部push进队列2中,最后的元素就是我们要pop出的元素,pop出后再把队列2中的数再放进队列1中。获取栈顶元素和方法和pop的方法相同。

用栈实现队列结构,同样要用两个栈来实现。一个栈用来poll数据,一个用来push数据。push时,都把数放进栈1中。poll时,把栈1的数据都放进栈2中,再poll。获取栈顶元素的方式和poll的方法相同。

代码如下所示:

public class StackAndQueueConvert {
	public static void main(String[] args) {
		
	}
	public static class TwoStacksQueue {
		private Stack<Integer> stackPush;
		private Stack<Integer> stackPop;
		public void push(int pushInt) {
			stackPush.push(pushInt);
		}
		public int poll() {
			if(stackPop.empty() && stackPush.empty()) {
				throw new RuntimeException("Queue is empty!");
			} else if (stackPop.empty()) {
				while(!stackPop.empty()) {
					stackPop.push(stackPush.pop());
				}
			}
			return stackPop.pop();
		}
		public int peek() {
			if(stackPop.empty() && stackPush.empty()) {
				throw new RuntimeException("Queue is empty!");
			} else if(stackPop.isEmpty()) {
				while(!stackPop.empty()) {
					stackPop.push(stackPush.pop());
				}
			}
			return stackPop.peek();
		}
	}
	public static class TwoQueuesStack {
		private Queue<Integer> queue;
		private Queue<Integer> help;
		
		public TwoQueuesStack() {
			queue = new LinkedList<Integer>();
			help = new LinkedList<Integer>();
		}
		
		public void push(int pushInt) {
			queue.add(pushInt);
		}
		
		public int peek() {
			if(queue.isEmpty()) {
				throw new RuntimeException("Stack is empty!");
			}
			while(queue.size() != 1) {
				help.add(queue.poll());
			}
			int res = queue.poll();
			help.add(res);
			swap();
			return res;
		}
		
		public int pop() {
			if(queue.isEmpty()) {
				throw new RuntimeException("Stack is empty!");
			}
			while(queue.size() > 1) {
				help.add(queue.poll());
			}
			int res = queue.poll();
			swap();
			return res;
		}
		
		private void swap() {
			Queue<Integer> tmp = help;
			help = queue;
			queue = tmp;
		}
	}
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值