队列——java实现

定义

现实生活中,我们去排队买东西,先排的先走,后排的后走。在程序中,这就是队列即先进先出(First in first out)表.


结构


实现


本文使用链表实现队列,如下:


package com.lemon.queue;

import java.util.NoSuchElementException;

/**
 * this class using linked list realize queue 
 * the feature of queue is first in first out,more specifically,
 * add operation only at the tail of queue and remove only at the top of queue.
 * @author an.yan
 * @param <T>
 */
public class MyQueue<T> {
	public static class Node<T>{
		private T value;
		private Node<T> next;
		public Node(T value, Node<T> next) {
			this.value = value;
			this.next = next;
		}
	}
	
	private int size;
	private Node<T> topOfQueue;
	public MyQueue(){
		topOfQueue=new Node<T>(null, null);
	}
	
	public boolean isEmpty(){
		return size==0;
	}
	
	
	/**
	 * add element to the tail of queue
	 * @param element
	 * @return
	 */
	 public boolean add(T element){  
         Node<T> node=new Node<T>(element, null);  
         if(size==0){  
             topOfQueue=node;
         }else{
             Node<T> temp=topOfQueue;  
             while(true){  
                 if(temp.next==null){  
                     break;  
                 }  
                 temp=temp.next;  
             }  
             temp.next=node;  
         }
         size++;  
         return true;  
     }  

	
	/**
	 * get and remove the value which at the top of current queue
	 * @return
	 */
	public T remove(){
		T t=topOfQueue.value;
		topOfQueue=topOfQueue.next;
		size--;
		return t;
	}
	
	/**
	 * return,but don't remove, the value which at the top of current queue
	 * @return
	 */
	public T element(){
		if(isEmpty()){
			throw new NoSuchElementException("current queue is null!");
		}
		return topOfQueue.value;
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		MyQueue<String> queue=new MyQueue<String>();
//		queue.add("a");
//		queue.add("b");
//		queue.add("c");
//		queue.add("d");
//		queue.add("e");
//		queue.add("f");
		/**
		 * test remove
		 */
//		while(!queue.isEmpty()){
//			System.out.println(queue.remove());
//		}
		
		/**
		 * test element()
		 */
		
		System.out.println(queue.element());
	}

}




应用

writing soon

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值