Java代码实现设计一个类实现自定义Queue接口方法
时间: 2024-05-14 09:17:48 浏览: 108
好的,下面是一个简单的Java代码实现,实现了一个自定义的Queue接口,具有常见的队列操作方法:
```java
public interface MyQueue<E> {
boolean add(E e);
boolean offer(E e);
E remove();
E poll();
E element();
E peek();
int size();
boolean isEmpty();
boolean contains(Object o);
boolean remove(Object o);
void clear();
}
```
接着是实现该接口的类`MyLinkedQueue`:
```java
public class MyLinkedQueue<E> implements MyQueue<E> {
private Node<E> head;
private Node<E> tail;
private int size;
private static class Node<E> {
E item;
Node<E> next;
Node(E item) {
this.item = item;
}
}
public boolean add(E e) {
Node<E> newNode = new Node<>(e);
if (tail == null) {
head = tail = newNode;
} else {
tail.next = newNode;
tail = newNode;
}
size++;
return true;
}
public boolean offer(E e) {
return add(e);
}
public E remove() {
if (head == null) {
throw new NoSuchElementException();
}
E item = head.item;
head = head.next;
if (head == null) {
tail = null;
}
size--;
return item;
}
public E poll() {
return (head == null) ? null : remove();
}
public E element() {
if (head == null) {
throw new NoSuchElementException();
}
return head.item;
}
public E peek() {
return (head == null) ? null : element();
}
public int size() {
return size;
}
public boolean isEmpty() {
return (head == null);
}
public boolean contains(Object o) {
for (Node<E> node = head; node != null; node = node.next) {
if (o == null) {
if (node.item == null) {
return true;
}
} else {
if (o.equals(node.item)) {
return true;
}
}
}
return false;
}
public boolean remove(Object o) {
Node<E> prev = null;
for (Node<E> node = head; node != null; prev = node, node = node.next) {
if (o == null) {
if (node.item == null) {
unlink(prev, node);
return true;
}
} else {
if (o.equals(node.item)) {
unlink(prev, node);
return true;
}
}
}
return false;
}
public void clear() {
for (Node<E> node = head; node != null; ) {
Node<E> next = node.next;
node.item = null;
node.next = null;
node = next;
}
head = tail = null;
size = 0;
}
private void unlink(Node<E> prev, Node<E> node) {
if (prev == null) {
head = node.next;
} else {
prev.next = node.next;
}
if (tail == node) {
tail = prev;
}
size--;
}
}
```
上述代码实现了一个基于链表的队列`MyLinkedQueue`,它是`MyQueue`接口的实现类,在这里我们也使用了内部类`Node`来表示队列中的每个元素节点。
阅读全文