数据结构-使用链表实现队列

使用链表实现队列

在这里插入图片描述

目录结构

在这里插入图片描述

Queue接口

package LinkedListQueue;


//队列
public interface Queue<E> {

    int getSize();

    boolean isEmpty();

    void enqueue(E e); //向队列中添加元素

    E dequeue(); //向队列中取出元素(出队)

    E getFront();//查看队首的元素
}

LinkedListQueue实现类

package LinkedListQueue;

/**
 * 带有尾节点的列表  实现队列
 *
 * @param <E>
 */
public class LinkedListQueue<E> implements Queue<E> {
    private class Node {
        public E e;
        public Node next;

        //      用户传来e 和 next
        public Node(E e, Node next) {
            this.e = e;
            this.next = next;
        }

        //      用户传来只传来e
        public Node(E e) {
            this(e, null);
        }

        //      用户没有传任何参数
        public Node() {
            this(null, null);
        }

        @Override
        public String toString() {
            return e.toString();
        }
    }


    private Node head, tail;
    private int size;

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

    @Override
    public int getSize() {
        return size;
    }

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

    //  入队操作
    @Override
    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 E dequeue() {
        if (isEmpty()) {
            throw new IllegalArgumentException("Cannot dequeue from an empty queue");
        }
        Node retNode = new Node();
        head = head.next;
        retNode.next = null;

        if (head == null) {
            tail = null;
        }
        size--;
        return retNode.e;
    }

    @Override
    public E getFront() {
        if (isEmpty()) {
            throw new IllegalArgumentException("Cannot dequeue from an empty queue");
        }
        return head.e;
    }

    @Override
    public String toString() {
        StringBuffer res = new StringBuffer();
        res.append("Queue: front ");
        Node cur = head;
        while (cur != null) {

            res.append(cur + "->");
            cur = cur.next;
        }
        res.append("NULL tail ");
        return res.toString();
    }

    public static void main(String[] args) {
        LinkedListQueue<Integer> queue = new LinkedListQueue<Integer>();
        for (int i = 0; i < 10; i++) {
            queue.enqueue(i);
            System.out.println(queue);
            //每入队列三个取出一个
            if (i % 3 == 2) {
                queue.dequeue();
                System.out.println(queue);
            }

        }
    }
}

测试:

在这里插入图片描述

发布了59 篇原创文章 · 获赞 9 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/qq_43229543/article/details/104034384