Java: 栈+递归实现队列功能和操作(add,poll,peek)

package offer;

import java.util.Stack;

public class Queue_rec {
	
	private Stack stack;
	
	public Queue_rec(){
		this.stack=new Stack();
	}
	
	public void add(int newNum){
		this.stack.push(newNum);
	}
	
	public boolean empty(){
		return this.stack.empty();
	}
	
	public int poll(){
		if(this.stack.empty()){
			throw new RuntimeException("Your queue is empty!");
		}
		int result=this.stack.pop();
		if(this.stack.empty()){
			return result;
		}else{
			int last=this.poll();
			this.stack.push(result);
			return last;
		}
	}
	
	public int peek(){
		if(this.stack.empty()){
			throw new RuntimeException("Your queue is empty!");
		}
		int result=this.stack.pop();
		if(this.stack.empty()){
			this.stack.push(result);
			return result;
		}else{
			int last=this.peek();
			this.stack.push(result);
			return last;
		}
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Queue_rec q=new Queue_rec();
		q.add(1);
		q.add(5);
		q.add(6);
		q.add(9);
		//System.out.println(q.peek());
		//System.out.println(q.peek());
		while(!q.empty()){
			System.out.println(q.poll());
		}
	}

}

你可能感兴趣的:(数据结构与算法,算法)