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()); } }
  • 相关阅读:
    数据库连接池-配置 wallfilter问题解决-UncategorizedSQLException
    maven统一配置
    maven依赖排除
    list排序
    spring boot日志配置
    HDU 5281 Senior's Gun (贪心)
    Saving HDU (贪心)
    切割木板 (贪心)
    查找最少标记点 (贪心)
    字典序最小问题 (贪心)
  • 原文地址:https://www.cnblogs.com/liujinhong/p/6513306.html
Copyright © 2011-2022 走看看