如何用队列结构实现栈结构

如何用队列结构实现栈结构(用两个队列)

package com.harrison.class02;

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

public class Code08_TwoQueuesImplementStack {
    
    
	public static class TwoQueueToStack<T> {
    
    
		public Queue<T> queue;
		public Queue<T> help;
		
		public TwoQueueToStack() {
    
    
			queue=new LinkedList<>();
			help=new LinkedList<>();
		}
		
		public void push(T value) {
    
    
			queue.offer(value);
		}
		
		public T poll() {
    
    
			while(queue.size()>1) {
    
    
				help.offer(queue.poll());
			}
			T ans=queue.poll();
			Queue<T> tmp=queue;
			queue=help;
			help=tmp;
			return ans;
		}
		
		public T peek() {
    
    
			while(queue.size()>1) {
    
    
				help.offer(queue.poll());
			}
			T ans=queue.poll();
			help.offer(ans);
			Queue<T> tmp=queue;
			queue=help;
			help=tmp;
			return ans;
		}
		
		public boolean isEmpty() {
    
    
			return queue.isEmpty();
		}
	}
	
	public static void main(String[] args) {
    
    
		System.out.println("test begin");
		TwoQueueToStack<Integer> myStack=new TwoQueueToStack<>();
		Stack<Integer> test=new Stack<Integer>();
		int testTimes=1000000;
		int max=1000000;
		for(int i=0; i<testTimes; i++) {
    
    
			if(myStack.isEmpty()) {
    
    
				if(!test.isEmpty()) {
    
    
					System.out.println("Oops");
				}else {
    
    
					int num=(int)(Math.random()*max);
					myStack.push(num);
					test.push(num);
				}
			}else {
    
    
				if(Math.random()<0.25) {
    
    
					int num=(int)(Math.random()*max);
					myStack.push(num);
					test.push(num);
				}else if(Math.random()<0.5) {
    
    
					if(!myStack.peek().equals(test.peek())) {
    
    
						System.out.println("Oops");
					}
				}else if(Math.random()<0.75) {
    
    
					if(!myStack.poll().equals(test.pop())) {
    
    
						System.out.println("Oops");
					}
				}else {
    
    
					if(myStack.isEmpty()!=test.isEmpty()) {
    
    
						System.out.println("Oops");
					}
				}
			}
		}
		System.out.println("finish");
	}
}

Guess you like

Origin blog.csdn.net/weixin_44337241/article/details/121571193