java之队列具体实现

1.队列是一种先进先出的线性的数据结构。

2.底层是数组的实现

package com.oop.collection.queue;

import java.util.Arrays;

public class MyQueue {

	// Define capacity constant: CAPACITY
	private static final int CAPACITY = 5;
	// Define capacity of queue
	private static int capacity;
	// Front of queue
	private static int front;
	// Tail of queue
	private static int tail;
	// Array for queue
	private static Object[] array;

	// Constructor of Queue class
	public MyQueue() {
		this.capacity = CAPACITY;
		array = new Object[capacity];
		front = tail = 0;
	}

	// Get size of queue
	public static int getSize() {
		if (isEmpty()) {
			return 0;
		}
		return (capacity + tail - front) % capacity;
	}

	// Whether is empty
	private static boolean isEmpty() {
		return (front == tail);
	}

	// put element into the end of queue
	public static void enqueue(Object element) throws RuntimeException {
		if (getSize() == capacity - 1)
			throw new RuntimeException("Queue is full");
		array[tail] = element;
		tail = (tail + 1) % capacity;
	}

	// get element from queue
	public static Object dequeue() throws RuntimeException {
		Object element;
		if (isEmpty())
			throw new RuntimeException("Queue is empty");
		element = array[front];
		front = (front + 1) % capacity;
		return element;
	}

	// Get the first element for queue
	public static Object frontElement() throws RuntimeException {
		if (isEmpty())
			throw new RuntimeException("Queue is empty");
		return array[front];
	}

	// Travel all elements of queue
	public static void getAllElements() {
		Object[] arrayList = new Object[getSize()];

		for (int i = front, j = 0; j < getSize(); i++, j++) {
			arrayList[j] = array[i];
		}
		System.out.println("All elements of queue: " + Arrays.toString(arrayList));
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值