让我们说我有一个大小为[10]的数组,当这个数组被填满时,我想实现一个FIFO结构,而不是它刚满,因此无法添加新的东西到阵列扔掉旧的。
例如,如果我有一个汽车制造商的String数组,当我的数组中有10个制造商时,我希望删除最旧的条目并添加最新的条目,但记住了FIFO。我将如何在这样的方法中实现它:
public void insert(String name)
{
int a;
a = (rear + 1) % names.length;
if(a == front)
{
System.out.println("Full Queue!");
}
else
{
rear = a;
names[rear] = name;
if(front == -1)
{
front = 0;
}
}
}
答案 0 :(得分:0)
我尝试使用后部和前部构建队列。轻微修改您的插入。我用一些测试写了一个main方法。
另外,我必须添加一个"空"标志,检查后面==前面是因为是空的还是因为已满。
public class DummyQueue {
int rear, front;
String[] names;
boolean empty = true;
public DummyQueue(int size) {
names = new String[size];
}
public void insert(String name)
{
if(!empty && rear == front )
{
System.out.println("Full Queue!");
}
else
{
names[rear] = name;
rear = (rear+1) % names.length;
}
empty = false;
}
public String deque()
{
if (empty) {
System.out.println("Empty Queue!");
return null; // demo
} else {
String response = names[front % names.length];
front = (front + 1) % names.length;
if (front == rear) empty = true;
return response;
}
}
public static void main(String[] args) {
DummyQueue d = new DummyQueue(10);
System.out.println(d.deque());
d.insert("Element");
System.out.println(d.deque());
System.out.println(d.deque());
for (int i = 0; i < 12; i++) {
System.out.println("Adding: "+i);
d.insert("Element "+ i);
}
for (int i = 0; i < 12; i++) {
System.out.println(d.deque());
}
}
}
答案 1 :(得分:0)
我建议使用LinkedList
public class LinkedList {
Node head;
Node tail;
final int MAX_SIZE;
int currentSize;
public LinkedList(int MAX_SIZE) {
this.head = null;
this.tail = null;
this.MAX_SIZE = MAX_SIZE;
this.currentSize = 0;
}
public void append(String val) {
Node n = new Node(val);
if (currentSize < MAX_SIZE) {
if (head == null) {
head = n;
tail = n;
return;
}
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = n;
currentSize++;
}
else {
head = head.next;
currentSize--;
append(val);
}
}
public class Node {
String val;
Node next;
public Node(String val) {
this.val = val;
this.next = null;
}
}
基本上你持有MAX_SIZE
和currentSize
。当你的currentSize达到最大值时,你移除LinkedList
的头部并将值附加到结尾。