单-双向队列

 

 

1 简图:

 



 

 

2 使用ArrayDeque队列模拟银行排队效果:

 

package Quene;

import java.util.ArrayDeque;
import java.util.Queue;

public class BackPosite {
	
	public static void main(String[] args) {
		
		Queue<Man> que = new ArrayDeque<Man>();
		for(int i=0; i<10; i++){
			final int num = i;
			que.offer(new Man(){ // 数据进入队列尾巴
				
				@Override
				public void deposit() {
					System.out.println("第" + num + "个人,办理存款业务,存款金额为: " + Math.random()*100 + "元");
				}
				
			});
		}
		
		dealWith(que);
	}

	private static void dealWith(Queue<Man> que) {
		Man man;
		while( (man = que.poll()) != null){ // 从队列头获取数值 并移除这个头对象 
			man.deposit();
		}
		
	}

}


interface Man {
	void deposit();
}

 

 

 

3 使用队列ArrayDeque 模拟堆栈效果:‘

 

package com.bjsxt.others.que;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * 使用队列实现自定义堆栈
 * 1、弹
 * 2、压
 * 3、获取头
 * @author Administrator
 *
 * @param <E>
 */
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();		
	}
}




package com.bjsxt.others.que;
//测试自定义堆栈   后进先出
public class Demo02 {

	/**
	 * 结果:
	 * 大小:3
www.sina.com
www.google.com
www.baidu.com
	 */
	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.youku.cn");  // 定义堆栈为3长度 这里在添加添加不进去
		 
		System.out.println("大小:"+backHistory.size()); // 结果为3
		
		//遍历
		String item=null;
		while(null!=(item=backHistory.pop())){
			System.out.println(item);
		}
	}

}


 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值