队列----java实现

FIFO:先进先出

存储单元:

public class Node {
    /*
    元素有两部分:
    元素
    下一个元素的引用
     */
    Object data;//数据域
    Node next; //指针域
    public Node(){}
    public Node(Object data,Node next){
        this.data=data;
        this.next=next;
    }
}

实现:

/**
 * Created by yaming 
 * 链式队列---链式存储实现
 */
public class LinkQueue {
    private Node first;//队列头,可以删除
    private Node last;//队列尾,可以插入
    private int size;
    /**
     * 是否为空
     * @return
     */
    public boolean isEmpty(){
        return size==0;
    }

    /**
     * 长度
     * @return
     */
    public int size(){
        return size;
    }

    /**
     * 入队
     * @param data
     * @return
     */
    public boolean push(Object data){
        Node node=new Node(data,null);
        //如果该链队列还是空链队列
        if (first == null) {
            first = node;
            last = first;//只有一个节点,front、rear都指向该节点
        } else {
            last.next = node;//让尾节点的next指向新增的节点
            last = node;//以新节点作为新的尾节点
        }
        size++;
        return true;
    }

    /**
     * 出队
     * @return
     */
    public Object pull(){
        Node node = first;
        first = first.next;
        node.next = null;
        size--;
        return node.data;
    }

    /**
     * 队列尾元素
     * @return
     */
    public Object getLast(){
        if(isEmpty()){
            return null;
        }
        return last.data;
    }
    public Object getFirst(){
        if(isEmpty()){
            return null;
        }
        return first.data;

    }
    public void clear(){
        first=null;
        last=null;
        size=0;
    }

    /**
     * 遍历
     * @return
     */
    public String queue(){
        if(isEmpty()){
            return "[]";
        }else {
            StringBuilder stringBuilder=new StringBuilder("[");
            for(Node current=first;current!=null;current=current.next){
                stringBuilder.append(current.data.toString()+", ");
            }
            int length=stringBuilder.length();
            return stringBuilder.delete(length-2,length).append("]").toString();
        }
    }
}
原文地址:https://www.cnblogs.com/inspred/p/8052358.html