自定义queue - linked & array


public class SimpleLinkedQueue {

	class Node{
		public String v;
		public Node next;
		
		public Node(String v){
			this.v = v;
		}
	}
	Node init = new Node(null);
	
	Node head = init;
	Node tail = init;
	
	
	public void put(String v){
		
		Node node = new Node(v);
		tail.next = node;
		tail = node;
		
	}
	
	public String take(){
// 第一次实现,head 只是一个空的节点,不包含数据,head的next才是第一个数据节点 ,下面四行实现没考虑到
//		String v = head.v;
//		Node tempHead = head.next;
//		head = tempHead;
//		return v;
		
		/**
		 * 第二次实现
		 * 1. 取出第一个数据节点 
		 * 2. 把head节点指针指向第一个数据节点, 并切断老的head 和 first的联系 , head ->/ first -> second ->...
		 *  
		 */
		
		Node oldHead = head;
		Node first = head.next;  //第一个数据节点
		String v = first.v;
		head = first;
		head.v = null;
		oldHead.next = null;
		return v;
	}
	
	
	public void readFromHead(){
		
		System.out.println("head is :" + head.v);
		
		Node n = head.next;
		while(n != null){
			System.out.println(n.v);
			n = n.next;
		}
	}
	
	public static void main(String args[]){
		SimpleLinkedQueue q = new SimpleLinkedQueue();
		for (int i = 0; i < 10; i++) {
			q.put("data-"+i);
		}
		
		System.out.println("take 1 : " + q.take());
		System.out.println("take 2 : " + q.take());
		
		q.readFromHead();
		
	}
}

// 未考虑线程安全,只做练习队列的写法
public class SimpleArrayQueue {

	public SimpleArrayQueue(){
		this(Integer.MAX_VALUE);
	}
	public SimpleArrayQueue(int length){
		list = new String[length];
	}
	
	
	private String[] list = null;  //队列
	
	private int take;  //take游标
	private int put;  //put游标
	
	private int count; //队列内元素数
	
	public void put(String e){
		
		if(count == list.length){
			System.out.println("队列满了,该清理了..,数据 " + e + " 被丢弃" );
			return;
		}
		
		list[put] = e;
		put++;
		count++;
		
		if(put == list.length)
			put = 0;
	}
	
	public String take(){
		if(count == 0){
			System.out.println("队列空了,还取个毛啊..");
			return null;
		}
		String e = list[take];
		list[take] = null;
		take++;
		count--;
		
		if(take == list.length)
			take = 0;
		
		return e;
	}
	
	public void read(){
		for(int i=0;i<list.length;i++){
			if(list[i] == null)
				continue;
			System.out.println("read : "+ i + " : " + list[i]);
		}
	}
	
	public static void main(String args[]){
		
		SimpleArrayQueue s = new SimpleArrayQueue(10);
		
		for(int i=0; i<8;i++){
			s.put("数"+i);
		}
		
		System.out.println("take 1 " + s.take());
		System.out.println("take 2 " + s.take());
		
		s.read();
		s.put("数***");
		s.put("数***1");
		System.out.println("take 3 " + s.take());
		s.put("数***2");
		
		s.read();
		
		
		
		
	}	
}

转载于:https://my.oschina.net/bihu/blog/790425

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值