Java queue through the stacks, queues achieve stack

How only queue structure to achieve stack structure?
         1, two ready queues: data help and
         2, the data is assumed to push data 1,2,3,4,5, when the need to poll 5, first help 1,2,3,4 add into the queue, when the data returns out of 5 poll
         3, and then perform swap, a data exchange properties help
         4, when the need to pop 4, steps 2 and 3 are basically the same and
how the queue structure stack architecture only?
         1, two stacks prepared: stackPush and stackPop
         2, is assumed to push the stack into five stackPush number: 1,2,3,4,5, then need to pop out of 1, all data first stackPush
               all add to stackPop then pop out by a return stackPop
         3, 2 need to pop out, steps consistent with 2
code is as follows:

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

public class StackAndQueueConvert_03 {

	//两个栈实现队列结构
	public static class TwoStacksQueue {
		private Stack<Integer> stackPush;
		private Stack<Integer> stackPop;

		public TwoStacksQueue() {
			stackPush = new Stack<Integer>();
			stackPop = new Stack<Integer>();
		}

		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 (!stackPush.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.empty()) {
				while (!stackPush.empty()) {
					stackPop.push(stackPush.pop());
				}
			}
			return stackPop.peek();
		}
	}

	//两个队列实现栈结构
	public static class TwoQueuesStack {
		private Queue<Integer> data;
		private Queue<Integer> help;

		public TwoQueuesStack() {
			data = new LinkedList<Integer>();
			help = new LinkedList<Integer>();
		}

		public void push(int pushInt) {
			data.add(pushInt);
		}

		public int peek() {
			if (data.isEmpty()) {
				throw new RuntimeException("Stack is empty!");
			}
			while (data.size() != 1) {
				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.add(data.poll());
			}
			int res = data.poll();
			swap();
			return res;
		}

		private void swap() {
			Queue<Integer> tmp = help;
			help = data;
			data = tmp;
		}

	}

}

 

Guess you like

Origin blog.csdn.net/qq_41544550/article/details/92803193