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());
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值