zoukankan      html  css  js  c++  java
  • Java队列的两种实现方式

    1. 基于数组

    package Algorithm.learn;
    
    import java.util.Arrays;
    
    /**
     * Created by liujinhong on 2017/3/7.
     */
    public class ArrayQueue<E> {
        Object[] queue;
        int size;
    
        public ArrayQueue() {
            queue = new Object[10];
        }
    
        public boolean isEmpty() {
            return size == 0;
        }
    
        public E poll() {
            if (isEmpty()) return null;
            E data = (E) queue[0];
            System.arraycopy(queue, 1, queue, 0, size-1);
            size--;
            return data;
        }
    
        private void ensureCapacity(int size) {
            if (size > queue.length) {
                int len = queue.length + 10;
                queue = Arrays.copyOf(queue, len);
            }
        }
    
        public void offer(E data) {
            ensureCapacity(size+1);
            queue[size++] = data;
        }
    
        public static void main(String[] args) {
            ArrayQueue<Integer>  queue = new ArrayQueue<>();
    
            for (int i = 0; i < 20; i++) {
                queue.offer(i);
            }
    
            for (int i = 0; i < 20; i++) {
                System.out.println(queue.poll());
            }
        }
    }

    2. 基于链表

    package Algorithm.learn;
    
    /**
     * Created by liujinhong on 2017/3/7.
     * 基于链表实现队列
     */
    public class ListQueue<E> {
        class Node<E> {
            Node<E> next = null;
            E data;
            public Node(E data) {
                this.data = data;
            }
        }
    
        private Node<E> head = null;
        private Node<E> tail = null;
    
        public boolean isEmpty() {
            return head == null;
        }
    
        public void offer(E e) {
            Node<E> node = new Node<E>(e);
            if (isEmpty()) {
                head = node;
                tail = node;
                return;
            }
            tail.next = node;
         tail = node; }
    public E poll() { if (isEmpty()) return null; E data = head.data; head = head.next; return data; } public int size() { Node<E> temp = head; int len = 0; while (temp != null) { len++; temp = temp.next; } return len; } public static void main(String[] args) { ListQueue<String> queue = new ListQueue<>(); queue.offer("a"); queue.offer("b"); System.out.println(queue.poll()); System.out.println(queue.poll()); } }
  • 相关阅读:
    [Python]小甲鱼Python视频第038课(类和对象:继承 )课后题及参考解答
    [Python]小甲鱼Python视频第037课(类和对象:面向对象编程 )课后题及参考解答
    [Python]小甲鱼Python视频第036课(类和对象:给大家介绍对象 )课后题及参考解答
    Session共享
    防止表单重复提交
    Docker安装redis
    Docker安装mysql
    docker-compose常用命令
    Docker常用命令
    Oracle 随机取记录
  • 原文地址:https://www.cnblogs.com/liujinhong/p/6513306.html
Copyright © 2011-2022 走看看