shz.core.queue.l.JLinkedQueue Maven / Gradle / Ivy
package shz.core.queue.l;
import shz.core.constant.ArrayConstant;
import shz.core.node.JSNode;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.LongConsumer;
/**
* 元素类型为long基于链表的队列
*
* 20+16*(n+1)(n为元素个数)
*
* B=8+16*(n+3)
*/
public class JLinkedQueue extends LinkedQueue {
private static final long serialVersionUID = 2797415927091859590L;
public static JLinkedQueue of() {
return new JLinkedQueue();
}
public final void offer(long e) {
JSNode temp = tail;
tail = JSNode.of(e);
if (head == null) head = tail;
else temp.next(tail);
++size;
}
public final long poll() {
checkEmpty();
long val = head.val;
head = head.next();
if (head == null) tail = null;
--size;
return val;
}
public final long head() {
checkEmpty();
return head.val;
}
public final long tail() {
checkEmpty();
return tail.val;
}
public final long[] toArray() {
if (size == 0) return ArrayConstant.EMPTY_LONG_ARRAY;
long[] array = new long[size];
int idx = 0;
JSNode current = head;
while (current != null) {
array[idx++] = current.val;
current = current.next();
}
return array;
}
public final void forEach(LongConsumer action) {
Objects.requireNonNull(action);
if (head != null) head.forEach((Consumer) node -> action.accept(node.val));
}
}