使用队列模拟银行存取钱和栈方法

1 使用队列模拟银行存取钱:

interface Request {
	void deposit();
}


public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		//File file = new File("D:\\kindle") ;
		//test(file,0);
		//test1();
		final Random random = new Random();
		
		Queue<Request> que = new ArrayDeque<>();
		for(int i=0; i<10; i++) { // 向队列中添加数据 
			final int num = i ; // 匿名内部类智能使用 final类型的变量 
			que.offer(new Request(){
				@Override
				public void deposit() {
					System.out.println("第" + num + " 人存款" + random.nextInt(20) + " W元");
				}
				
			});
		}
		dealWith(que);
	}
	
	
	
	/**
第0 人存款4 W元
第1 人存款18 W元
第2 人存款3 W元
第3 人存款17 W元
第4 人存款16 W元
第5 人存款7 W元
第6 人存款3 W元
第7 人存款7 W元
第8 人存款4 W元
第9 人存款1 W元
	 * @param que
	 */
	private static void dealWith(Queue<Request> que) {
		 Request req =null;
		while( null != (req = (Request)que.poll())) { // 从队列中 先进先出 消费队列中数据
			req.deposit();
		}
	}
 
 
 

2 使用队列模拟栈压栈 弹出:

public class MyStack<E> {
	//容器
	private Deque<E> container =new ArrayDeque<E>();
	//容量
	private int cap;
	public MyStack(int cap) {
		super();
		this.cap = cap;
	}
	
	//压栈
	public boolean push(E e){
		if(container.size()+1>cap){
			return false;
		}
		return container.offerLast(e);
		
	}
	//弹栈
	public E pop(){
		return container.pollLast();
	}
	//获取
	public E peek(){
		return container.peekLast();
	}
	
	public int size(){
		return this.container.size();		
	}
}


测试方法

	public static void main(String[] args) {
		MyStack<String> backHistory =new MyStack<String>(3); //如果超过范围 则不能在插入 
		backHistory.push("www.baidu.com");
		backHistory.push("www.google.com");
		backHistory.push("www.sina.com");
		backHistory.push("www.lele.cn");
		
		System.out.println("大小:"+backHistory.size());
		
		//遍历
		String item=null;
		while(null!=(item=backHistory.pop())){
			System.out.println(item);
		}
	}

猜你喜欢

转载自chengjianxiaoxue.iteye.com/blog/2399105