Finish AB 2

This commit is contained in:
2022-03-28 10:13:19 +02:00
parent 5158aa2cbe
commit dca869995a
4 changed files with 151 additions and 32 deletions

@ -5,13 +5,20 @@
//
public class BodyQueue {
//TODO: declare variables.
private int capacity;
private int head = 0;
private int tail = 0;
private Body[] queue;
public BodyQueue() {
this(4);
}
// Initializes this queue with an initial capacity.
// Precondition: initialCapacity > 0.
public BodyQueue(int initialCapacity) {
//TODO: define constructor.
this.capacity = initialCapacity;
this.queue = new Body[this.capacity];
}
// Initializes this queue as an independent copy of the specified queue.
@ -19,28 +26,50 @@ public class BodyQueue {
// and vice versa.
// Precondition: q != null.
public BodyQueue(BodyQueue q) {
//TODO: define constructor.
this.capacity = q.capacity;
this.head = q.size();
this.tail = 0;
this.queue = new Body[this.capacity];
for (int i = 0; i < q.size(); i++) {
this.queue[i] = q.queue[i];
}
}
// Adds the specified body 'b' to this queue.
public void add(Body b) {
//TODO: implement method.
queue[head] = b;
head = (head + 1) % capacity;
if (head == tail) {
doubleCapacity();
head = capacity / 2;
}
}
// Retrieves and removes the head of this queue, or returns 'null'
// if this queue is empty.
public Body poll() {
//TODO: implement method.
return null;
if (tail == head) {
return null;
}
Body b = queue[tail];
queue[tail] = null;
tail = (tail + 1) % capacity;
return b;
}
// Returns the number of bodies in this queue.
public int size() {
return (head - tail + capacity) % capacity;
}
//TODO: implement method.
return -1;
private void doubleCapacity() {
Body[] tmp = new Body[capacity * 2];
for (int i = head, j = 0; i < tail + capacity; i++, j++) {
tmp[j] = queue[i % capacity];
}
head = capacity;
tail = 0;
capacity *= 2;
queue = tmp;
}
}