使用链表实现队列,两个指针,一个尾指针负责入队,一个头指针负责出队,比较简单,代码如下:
package com.freshbin.dataStructAndAlgo.chapter06.mycode.queue;
/**
* 链表实现队列
* @author freshbin
* @date 2020/4/14 17:32
*/
public class QueueBasedOnLinkedList {
private Node headNode;
private Node tailNode;
public QueueBasedOnLinkedList() {
}
public void enqueue(String value) {
System.out.println("准备加入队列的数据:" + value);
Node newNode = new Node(value);
if(tailNode == null) {
tailNode = newNode;
headNode = newNode;
return;
}
tailNode.next = newNode;
tailNode = tailNode.next;
}
public String dequeue() {
if(headNode == null) {
System.out.println("队列为空");
return null;
}
String returnData = headNode.data;
headNode = headNode.next;
System.out.println("准备出队的数据:" + returnData);
return returnData;
}
public static void main(String[] arg) {
String a = "a";
String b = "b";
QueueBasedOnLinkedList queueBasedOnLinkedList = new QueueBasedOnLinkedList();
queueBasedOnLinkedList.dequeue();
queueBasedOnLinkedList.enqueue(a);
queueBasedOnLinkedList.enqueue(b);
queueBasedOnLinkedList.dequeue();
queueBasedOnLinkedList.dequeue();
queueBasedOnLinkedList.dequeue();
}
public class Node {
private String data;
private Node next;
public Node() {
}
public Node(String value) {
this.data = value;
}
public String getData() {
return this.data;
}
public void setData(String data) {
this.data = data;
}
public Node getNext() {
return this.next;
}
public void setNext(Node next) {
this.next = next;
}
}
}
使用数组实现循环队列,这里主要是使用了一个公式判断是否队满(tail+1)%size=head,不过这会导致队列有一个空位不能使用,代码如下:
package com.freshbin.dataStructAndAlgo.chapter06.mycode.queue;
/**
* 数组实现循环队列
*
* 队列满的条件为:(tail+1)%size=head
* 队列空的条件为:head=tail
* tail为当前尾结点索引,head为当前头结点索引,size为队列大小
* @author freshbin
* @date 2020/4/14 17:51
*/
public class CircularQueue {
private Integer size;
private String[] dataArray;
private Integer head;
private Integer tail;
public CircularQueue() {
this(3);
}
public CircularQueue(int maxSize) {
this.size = maxSize+1;
dataArray = new String[this.size];
head = 0;
tail = 0;
}
public void enquue(String value) {
if((tail + 1) % size == head) {
System.out.println("队列满");
return;
}
dataArray[tail] = value;
tail = (tail + 1) % size;
}
public String dequeue() {
if(tail == head) {
System.out.println("队空!");
return null;
}
String returnValue = dataArray[head];
head = (head + 1) % size;
return returnValue;
}
public static void main(String[] arg) {
CircularQueue circularQueue = new CircularQueue();
circularQueue.dequeue();
for(int i = 0; i < 4; i++) {
circularQueue.enquue("queue" + i);
}
System.out.println("出队列元素:");
String dequeueData = circularQueue.dequeue();
while (dequeueData != null) {
System.out.print(dequeueData + " ");
dequeueData = circularQueue.dequeue();
}
}
}