队列Queue的实现
数组实现
package DataStructures.Queues; /**
* This implements Queues by using the class Queue.
* <p>
* A queue data structure functions the same as a real world queue.
* The elements that are added first are the first to be removed.
* New elements are added to the back/rear of the queue.
*
*/
class Queue {
/**
* Default initial capacity.
*/
private static final int DEFAULT_CAPACITY = 10; /**
* Max size of x`the queue
*/
private int maxSize;
/**
* The array representing the queue
*/
private int[] queueArray;
/**
* Front of the queue
*/
private int front;
/**
* Rear of the queue
*/
private int rear;
/**
* How many items are in the queue
*/
private int nItems; /**
* init with DEFAULT_CAPACITY
*/
public Queue() {
this(DEFAULT_CAPACITY);
} /**
* Constructor
*
* @param size Size of the new queue
*/
public Queue(int size) {
maxSize = size;
queueArray = new int[size];
front = 0;
rear = -1;
nItems = 0;
} /**
* Inserts an element at the rear of the queue
*
* @param x element to be added
* @return True if the element was added successfully
*/
public boolean insert(int x) {
if (isFull())
return false;
// If the back of the queue is the end of the array wrap around to the front
rear = (rear + 1) % maxSize;
queueArray[rear] = x;
nItems++;
return true;
} /**
* Remove an element from the front of the queue
*
* @return the new front of the queue
*/
public int remove() {
if (isEmpty()) {
return -1;
}
int temp = queueArray[front];
front = (front + 1) % maxSize;
nItems--;
return temp;
} /**
* Checks what's at the front of the queue
*
* @return element at the front of the queue
*/
public int peekFront() {
return queueArray[front];
} /**
* Checks what's at the rear of the queue
*
* @return element at the rear of the queue
*/
public int peekRear() {
return queueArray[rear];
} /**
* Returns true if the queue is empty
*
* @return true if the queue is empty
*/
public boolean isEmpty() {
return nItems == 0;
} /**
* Returns true if the queue is full
*
* @return true if the queue is full
*/
public boolean isFull() {
return nItems == maxSize;
} /**
* Returns the number of elements in the queue
*
* @return number of elements in the queue
*/
public int getSize() {
return nItems;
} @Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = front; ; i = ++i % maxSize) {
sb.append(queueArray[i]).append(", ");
if (i == rear) {
break;
}
}
sb.replace(sb.length() - 2, sb.length(), "]");
return sb.toString();
}
} /**
* This class is the example for the Queue class
*
* @author Unknown
*/
public class Queues {
/**
* Main method
*
* @param args Command line arguments
*/
public static void main(String[] args) {
Queue myQueue = new Queue(4);
myQueue.insert(10);
myQueue.insert(2);
myQueue.insert(5);
myQueue.insert(3);
// [10(front), 2, 5, 3(rear)] System.out.println(myQueue.isFull()); // Will print true myQueue.remove(); // Will make 2 the new front, making 10 no longer part of the queue
// [10, 2(front), 5, 3(rear)] myQueue.insert(7); // Insert 7 at the rear which will be index 0 because of wrap around
// [7(rear), 2(front), 5, 3] System.out.println(myQueue.peekFront()); // Will print 2
System.out.println(myQueue.peekRear()); // Will print 7
System.out.println(myQueue.toString()); // Will print [2, 5, 3, 7]
}
}
链表实现
package DataStructures; import java.util.NoSuchElementException; public class LinkedQueue {
class Node {
int data;
Node next; public Node() {
this(0);
} public Node(int data) {
this(data, null);
} public Node(int data, Node next) {
this.data = data;
this.next = next;
}
} /**
* Front of Queue
*/
private Node front; /**
* Rear of Queue
*/
private Node rear; /**
* Size of Queue
*/
private int size; /**
* Init LinkedQueue
*/
public LinkedQueue() {
front = rear = new Node();
} /**
* Check if queue is empty
*
* @return <tt>true</tt> if queue is empty, otherwise <tt>false</tt>
*/
public boolean isEmpty() {
return size == 0;
} /**
* Add element to rear of queue
*
* @param data insert value
* @return <tt>true</tt> if add successfully
*/
public boolean enqueue(int data) {
Node newNode = new Node(data);
rear.next = newNode;
rear = newNode; /* make rear point at last node */
size++;
return true;
} /**
* Remove element at the front of queue
*
* @return element at the front of queue
*/
public int dequeue() {
if (isEmpty()) {
throw new NoSuchElementException("queue is empty");
}
Node destroy = front.next;
int retValue = destroy.data;
front.next = front.next.next;
destroy = null; /* clear let GC do it's work */
size--; if (isEmpty()) {
front = rear;
} return retValue;
} /**
* Peek element at the front of queue without removing
*
* @return element at the front
*/
public int peekFront() {
if (isEmpty()) {
throw new NoSuchElementException("queue is empty");
}
return front.next.data;
} /**
* Peek element at the rear of queue without removing
*
* @return element at the front
*/
public int peekRear() {
if (isEmpty()) {
throw new NoSuchElementException("queue is empty");
}
return rear.data;
} /**
* Return size of queue
*
* @return size of queue
*/
public int size() {
return size;
} /**
* Clear all nodes in queue
*/
public void clear() {
while (!isEmpty()) {
dequeue();
}
} @Override
public String toString() {
if (isEmpty()) {
return "[]";
}
StringBuilder builder = new StringBuilder();
Node cur = front.next;
builder.append("[");
while (cur != null) {
builder.append(cur.data).append(", ");
cur = cur.next;
}
builder.replace(builder.length() - 2, builder.length(), "]");
return builder.toString();
} /* Driver Code */
public static void main(String[] args) {
LinkedQueue queue = new LinkedQueue();
assert queue.isEmpty(); queue.enqueue(1); /* 1 */
queue.enqueue(2); /* 1 2 */
queue.enqueue(3); /* 1 2 3 */
System.out.println(queue); /* [1, 2, 3] */ assert queue.size() == 3;
assert queue.dequeue() == 1;
assert queue.peekFront() == 2;
assert queue.peekRear() == 3; queue.clear();
assert queue.isEmpty(); System.out.println(queue); /* [] */
}
}
优先级队列,这里采用的是整体移动,好像数组也只能这么做
package DataStructures.Queues; /**
* This class implements a PriorityQueue.
* <p>
* A priority queue adds elements into positions based on their priority.
* So the most important elements are placed at the front/on the top.
* In this example I give numbers that are bigger, a higher priority.
* Queues in theory have no fixed size but when using an array
* implementation it does.
*/
class PriorityQueue {
/**
* The max size of the queue
*/
private int maxSize;
/**
* The array for the queue
*/
private int[] queueArray;
/**
* How many items are in the queue
*/
private int nItems; /**
* Constructor
*
* @param size Size of the queue
*/
public PriorityQueue(int size) {
maxSize = size;
queueArray = new int[size];
nItems = 0;
} /**
* Inserts an element in it's appropriate place
*
* @param value Value to be inserted
*/
public void insert(int value) {
if (isFull()) {
throw new RuntimeException("Queue is full");
} else {
int j = nItems - 1; // index of last element
while (j >= 0 && queueArray[j] > value) {
queueArray[j + 1] = queueArray[j]; // Shifts every element up to make room for insertion
j--;
}
queueArray[j + 1] = value; // Once the correct position is found the value is inserted
nItems++;
}
} /**
* Remove the element from the front of the queue
*
* @return The element removed
*/
public int remove() {
return queueArray[--nItems];
} /**
* Checks what's at the front of the queue
*
* @return element at the front of the queue
*/
public int peek() {
return queueArray[nItems - 1];
} /**
* Returns true if the queue is empty
*
* @return true if the queue is empty
*/
public boolean isEmpty() {
return (nItems == 0);
} /**
* Returns true if the queue is full
*
* @return true if the queue is full
*/
public boolean isFull() {
return (nItems == maxSize);
} /**
* Returns the number of elements in the queue
*
* @return number of elements in the queue
*/
public int getSize() {
return nItems;
}
} /**
* This class implements the PriorityQueue class above.
*
* @author Unknown
*/
public class PriorityQueues {
/**
* Main method
*
* @param args Command Line Arguments
*/
public static void main(String[] args) {
PriorityQueue myQueue = new PriorityQueue(4);
myQueue.insert(10);
myQueue.insert(2);
myQueue.insert(5);
myQueue.insert(3);
// [2, 3, 5, 10] Here higher numbers have higher priority, so they are on the top for (int i = 3; i >= 0; i--)
System.out.print(myQueue.remove() + " "); // will print the queue in reverse order [10, 5, 3, 2] // As you can see, a Priority Queue can be used as a sorting algotithm
}
}
ArrayList实现,add加最后,get随意,remove随意,很简单了
package DataStructures.Queues; import java.util.ArrayList; /**
* This class implements a GenericArrayListQueue.
* <p>
* A GenericArrayListQueue data structure functions the same as any specific-typed queue.
* The GenericArrayListQueue holds elemets of types to-be-specified at runtime.
* The elements that are added first are the first to be removed (FIFO)
* New elements are added to the back/rear of the queue.
*
*/
public class GenericArrayListQueue<T> {
/**
* The generic ArrayList for the queue
* T is the generic element
*/
ArrayList<T> _queue = new ArrayList<T>(); /**
* Checks if the queue has elements (not empty)
*
* @return True if the queue has elements. False otherwise.
*/
private boolean hasElements() {
return !_queue.isEmpty();
} /**
* Checks what's at the front of the queue
*
* @return If queue is not empty, element at the front of the queue. Otherwise, null
*/
public T peek() {
T result = null;
if(this.hasElements()) { result = _queue.get(0); }
return result;
} /**
* Inserts an element of type T to the queue.
*
* @param element of type T to be added
* @return True if the element was added successfully
*/
public boolean add(T element) {
return _queue.add(element);
} /**
* Retrieve what's at the front of the queue
*
* @return If queue is not empty, element retrieved. Otherwise, null
*/
public T poll() {
T result = null;
if(this.hasElements()) { result = _queue.remove(0); }
return result;
} /**
* Main method
*
* @param args Command line arguments
*/
public static void main(String[] args) {
GenericArrayListQueue<Integer> queue = new GenericArrayListQueue<Integer>();
System.out.println("Running...");
assert queue.peek() == null;
assert queue.poll() == null;
assert queue.add(1) == true;
assert queue.peek() == 1;
assert queue.add(2) == true;
assert queue.peek() == 1;
assert queue.poll() == 1;
assert queue.peek() == 2;
assert queue.poll() == 2;
assert queue.peek() == null;
assert queue.poll() == null;
System.out.println("Finished.");
}
}
暂时实现这些,队列其实是个常用的在业务场景。要理解。
队列Queue的实现的更多相关文章
- Python进阶【第二篇】多线程、消息队列queue
1.Python多线程.多进程 目的提高并发 1.一个应用程序,可以有多进程和多线程 2.默认:单进程,单线程 3.单进程,多线程 IO操作,不占用CPU python的多线程:IO操作,多线程提供并 ...
- Java中的队列Queue,优先级队列PriorityQueue
队列Queue 在java5中新增加了java.util.Queue接口,用以支持队列的常见操作.该接口扩展了java.util.Collection接口. Queue使用时要尽量避免Collecti ...
- jquery 的队列queue
使用示列代码: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www ...
- Windows Azure Service Bus (2) 队列(Queue)入门
<Windows Azure Platform 系列文章目录> Service Bus 队列(Queue) Service Bus的Queue非常适合分布式应用.当使用Service Bu ...
- Windows Azure Service Bus (3) 队列(Queue) 使用VS2013开发Service Bus Queue
<Windows Azure Platform 系列文章目录> 在之前的Azure Service Bus中,我们已经介绍了Service Bus 队列(Queue)的基本概念. 在本章中 ...
- (C#)使用队列(Queue)解决简单的并发问题
(C#)使用队列(Queue)解决简单的并发问题 2015-07-16 13:04 13265人阅读 评论(8) 收藏 举报 分类: Asp.Net(8) 版权声明:本文为博主原创文章,未经博主允 ...
- STL中的单向队列queue
转载自:http://blog.csdn.net/morewindows/article/details/6950917 stl中的queue指单向队列,使用时,包含头文件<queue>. ...
- java09 队列Queue与Deque
队列Queue与Deque. Enumeration Hashtable与Hashtable子类Properties(资源配置文件) 引用类型(强.软.弱.虚)与WeakHashMap Identit ...
- 队列Queue和栈
1.队列Queue是常用的数据结构,可以将队列看成特殊的线性表,队列限制了对线性表的访问方式,只能从线性表的一段添加(offer)元素, 从另一段取出(poll)元素,队列遵循先进先出的原则. 2.J ...
- 消息队列Queue大全
消息队列Queue大全 (http://queues.io/) 作业队列,消息队列和其他队列.几乎所有你能想到的都在这. 关于 那里有很多排队系统.他们每个人都不同,是为解决某些问题而创建的.这个页面 ...
随机推荐
- [debug] 解决pycharm中无法import自己建立的模块问题
修改文件夹属性,将其改为"resource",就可以来import了.
- ASP.NET MVC5基础 - Global.asax详解
简介 作用 Global.asax的处理事件 实例说明 总结 简介 Global.asax是一个文本文件,它提供全局可用代码.这些代码包括应用程序的事件处理程序以及会话事件.方法和静态变量.有时该文件 ...
- TensorFlow实现图像卷积并可视化示例
图片尺寸要自己修改. 看起来好像没啥意思,不知道下一步能干什么,先卷了再说.由于weights是随机生成的(tf.random_normal作用:用于从服从指定正太分布的数值中取出随机数),所以每次卷 ...
- 利用Python写一个抽奖程序,解密游戏内抽奖的秘密
前言 本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 作者: 极客挖掘机 PS:如有需要Python学习资料的小伙伴可以加点击下 ...
- P1356 数列的整除性
dp百题进度条[2/100] 题目链接 题目描述 对于任意一个整数数列,我们可以在每两个整数中间任意放一个符号'+'或'-',这样就可以构成一个表达式,也就可以计算出表达式的值.比如,现在有一个整数数 ...
- 一文读懂AOE到底是什么!
一.背景 1.1 AoE是什么 AoE (AI on Edge) 是一个滴滴开源的终端侧AI集成运行时环境(IRE).以 “稳定性.易用性.安全性” 为设计原则,帮助开发者将不同框架的深度学习算法轻松 ...
- 5.Ansible Jinja2 模板
1.jinja2渲染NginxProxy配置文件 jinja2 房屋建筑设计固定的 jinja2模板与Ansible关系 Ansible如何使用jinja2模板 template模块 拷贝文件? te ...
- 数据库三,exec内置函数
数据库三,exec内置函数 一.数据库查询与执行顺序 必备知识 查询语句的基本操作 - select - from - where - group by - having - distinct - o ...
- pyecharts绘制地图
python 绘制地图 环境准备 1.1 安装必备绘画库 亲身体验,最新版的pyecharts使用不来,通过百度寻得的教学推荐版本 0.1.9.4 可以绘制完成世界地图,国家地图以及市级地图,但是不能 ...
- MySQL数据库:函数的应用
字符串截取 # 从左边开始 第1个字符 left(字段名,1) # 从那里开始,截取几个 substring(字段名,1,1) str函数 # 连接字符串 concat(s1,s2,s3,--,sn) ...