JAVA数据结构之链表实现队列

用链表实现队列

接口

public interface Queue<E> {
    int getSize();
    boolean isEmpty();
    void enqueue(E e);
    E dequeue();
    E getFront();
}

链表实现代码

public class LinkedListQueue<E> implements Queue<E>{
    //需要建立头结点,尾结点
    //头结点侧作为队列的队首
    //尾结点侧作为队列的队尾
    private Node head, tail;
    private int size;

    public LinkedListQueue(){
        head = null;
        tail = null;
        size = 0;
    }

    public int getSize() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public E getFront(){
        if(isEmpty()){
            throw new IllegalArgumentException("Queue is empty");
        }
        return head.e;
    }

    public E dequeue() {
        if(isEmpty()){
            throw new IllegalArgumentException("Cannot dequeue from an empty queue.");
        }
        Node retNode = head;
        head = head.next;
        retNode.next = null;

        if (head == null) {
            //此时为空时
            tail = null;
        }
        size--;
        return retNode.e;
    }
    public void enqueue(E e) {
    //说明队列无元素
       if(tail == null){
          tail = new Node(e);
          head = tail;
       }else{
           tail.next = new Node(e);
           tail = tail.next;
       }
        size++;
    }
    @Override
    public String toString() {

        StringBuilder res = new StringBuilder();
        res.append("Queue:front");

        Node cur = head;
        while (cur != null) {
            res.append(cur + "->");
            cur = cur.next;
        }
        //for(Node cur = dummyHead.next; cur != null; cur = cur.next){ res.append(cur+"->");}
        res.append("null tail");
        return res.toString();
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_41263632/article/details/81781201