public class SpecialQueue<ELEMENT> {
private ELEMENT[] data;
private int head;
private int tail;
private int count;
public SpecialQueue() {
this(10);
}
public SpecialQueue(int capacity) {
this.data = (ELEMENT[]) new Object[capacity];
this.head = 0;
this.tail = 0;
this.count = 0;
}
// Equivalent to Count property in C#
public int size() {
return this.count;
}
private int Next(int position) {
return (++position >= this.data.length)? 0: position;
}
// Equivalent to Enqueue method in C#
public void add(ELEMENT element) {
if (this.count >= this.data.length) {
throw new RuntimeException("La cola está llena...");
}
this.data[this.tail] = element;
this.tail = this.Next(this.tail);
++this.count;
}
// Equivalent to Dequeue method in C#
public ELEMENT remove() {
if (this.count <= 0) {
throw new RuntimeException("La cola está vacía...");
}
ELEMENT temp = this.data[this.head];
this.head = this.Next(this.head);
--this.count;
return temp;
}
public ELEMENT[] toArray() {
ELEMENT[] result = (ELEMENT[]) new Object[this.size()];;
for (int pos = this.head, c = 0; c < this.count; c++) {
result[c] = this.data[pos];
pos = this.Next(pos);
}
return result;
}
public SpecialQueue<ELEMENT> join(SpecialQueue<ELEMENT> other) {
SpecialQueue<ELEMENT> result =
new SpecialQueue<ELEMENT>((this.size() + other.size()) * 2);
ELEMENT[] data = this.toArray();
for (ELEMENT e : data) {
result.add(e);
}
data = other.toArray();
for (ELEMENT e : data) {
result.add(e);
}
return result;
}
}
Comments