队列——java实现

来源:互联网 发布:网络漫画家收入 编辑:程序博客网 时间:2024/05/16 11:34

定义

现实生活中,我们去排队买东西,先排的先走,后排的后走。在程序中,这就是队列即先进先出(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

原创粉丝点击