队列实现栈,栈实现队列

两个队列实现栈

   每次进入一个队列,取出得时候,把所有元素进入另一个队列,只留下一个元素,以此实现栈的先进后出(FILO)。

package algorithmByMySelf;

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

/* 用两个队列实现一个栈
 * 
 * */

public class twoQueueToStack {
	private Queue<Integer> data;
	private Queue<Integer> help;
	
	public twoQueueToStack() {
		data = new LinkedList<Integer>();
		help = new LinkedList<Integer>();
	}
	
	public void push(int num) {
		data.add(num);
	}
	
	public int peek() {  //取但不删
		if(data.isEmpty()) {
//			System.out.println("this is a empty Queue!");
			throw new RuntimeException("this is a empty Queue! thank you!");
		}
		while(data.size() > 1) {
			help.add(data.poll());
		}
		int res = data.poll();
		help.add(res);
		swap();
		return res;
	}
	
	public int pop() { // 取且删
		if(data.isEmpty()) {
//			System.out.println("this is a empty Queue!");
			throw new RuntimeException("this is a empty Queue! thank you!");
		}
		while(data.size() > 1) {
			help.add(data.poll());
		}
		int res = data.poll();
		swap();
		return res;
		
	}
	public void swap() {
		Queue<Integer> temp = data;
//		temp = data;
		data = help;
		help = temp;
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		twoQueueToStack teStack = new twoQueueToStack();
		teStack.push(1);
		teStack.push(2);
		teStack.push(3);
		System.out.println(teStack.peek());
		System.out.println(teStack.pop());
		System.out.println(teStack.pop());
		System.out.println(teStack.peek());
	}

}

两个栈实现队列

  注意stackPush倾倒至stackPop中时,第一stackPop要为空, 第二stackPush要全部倒进去!

package algorithmByMySelf;

import java.util.Stack;

/*
 * 注意stackPush倾倒至stackPop中时,
 * 第一stackPop要为空,
 * 第二stackPush要全部倒进去!
 * */

public class TwoStackToQueue {

	private Stack<Integer> stackPush;
	private Stack<Integer> stackPop;
	
	public TwoStackToQueue() {
		stackPush = new Stack<Integer>();
		stackPop = new Stack<Integer>();
		
	}
	
	public void push(int num) {
		stackPush.push(num);
		dao();
	}
	
	public int poll() {
		if(stackPop.isEmpty() && stackPush.isEmpty()) {
			throw new RuntimeException("this is a empty Queue!");
		}else if(stackPop.isEmpty()) {
			dao();
		}
		return stackPop.pop();
	}
	
	public int peek() {
		if(stackPop.isEmpty() && stackPush.isEmpty()) {
			throw new RuntimeException("this is a empty Queue!");
		}else if(stackPop.isEmpty()) {
			dao();
		}
		return stackPop.peek();
	}
	
	public void dao() {  // 把stackstack中的元素,倾倒stackpop
		if(!stackPop.isEmpty()) {  
			return;
		}
		while(!stackPush.isEmpty()) {
			stackPop.push(stackPush.pop());
		}
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TwoStackToQueue teStackToQueue = new TwoStackToQueue();
		teStackToQueue.push(1);
		teStackToQueue.push(2);
		teStackToQueue.push(3);
		System.out.println(teStackToQueue.peek());
		System.out.println(teStackToQueue.poll());
		System.out.println(teStackToQueue.poll());
		System.out.println(teStackToQueue.poll());
	}

}

 

posted @ 2019-01-04 00:15  Horken  阅读(668)  评论(0编辑  收藏  举报