/**
* 使用链表实现队列
* @param <E>
*/
public class LinkedQueue<E> implements Queue<E> {
public static void main(String[] a) {
LinkedQueue<Integer> list = new LinkedQueue<>();
for (int i = 0; i < 5; i++) {
list.enqueue(i);
System.out.println(list);
}
list.dequeue();
System.out.println(list);
}
//队首对象,队尾对象
Node head, tail;
int size;
@Override
public int getSize() {
return size;
}
@Override
public boolean isEmpty() {
return size == 0;
}
//入队
@Override
public void enqueue(E o) {
//队尾为null,整个链表为null
if (tail == null) {
tail = new Node(o);
head = tail;
} else {
tail.next = new Node(o);
tail = tail.next;
}
size++;
}
//出队(移除队首)
@Override
public E dequeue() {
if (isEmpty())
throw new IllegalArgumentException("list is null");
Node ret = head;
head = head.next;
ret.next = null;
if (head == null) {
tail = null;
}
size--;
return ret.e;
}
//获取队首
@Override
public E getFront() {
if (isEmpty())
throw new IllegalArgumentException("list is null");
return head.e;
}
@NonNull
@Override
public String toString() {
StringBuilder ret = new StringBuilder();
ret.append("LinkedQueue ");
ret.append("[");
Node pre = head;
for (int i = 0; i < size; i++) {
ret.append("<---"+pre.e);
pre = pre.next;
}
ret.append("]");
return ret.toString();
}
class Node {
E e;
Node next;
public Node(E e, Node next) {
this.e = e;
this.next = next;
}
public Node(E e) {
this.e = e;
this.next = null;
}
public Node() {
this.e = null;
this.next = null;
}
@Override
public String toString() {
return e.toString();
}
}
}
链表实现队列LinkedQueue
最新推荐文章于 2023-12-15 22:05:29 发布