队列,先进先出结构
增
public void offer(E data){
Node<E> node = new Node<>(data);
if (head.next == null) {
rear = head;
}
while (rear.next != null){
rear = rear.next;
}
rear.next = node;
rear = node;
rear.next = null;
}
删
public E poll(){
if (isEmpty()){
throw new RuntimeException("队列为空");
}
E e = head.next.data;
head.next = head.next.next;
return e;
}
查
public E peek(){
if (isEmpty()) {
throw new RuntimeException("队列为空");
}
return head.next.data;
}
总览
package com.collection;
public class LinkedQueue<E> {
private Node<E> head = new Node<>(null);
private Node<E> rear = new Node<>(null);
public void offer(E data){
Node<E> node = new Node<>(data);
if (head.next == null) {
rear = head;
}
while (rear.next != null){
rear = rear.next;
}
rear.next = node;
rear = node;
rear.next = null;
}
public E poll(){
if (isEmpty()){
throw new RuntimeException("队列为空");
}
E e = head.next.data;
head.next = head.next.next;
return e;
}
public E peek(){
if (isEmpty()) {
throw new RuntimeException("队列为空");
}
return head.next.data;
}
public boolean isEmpty() {
return head.next == null;
}
private static class Node<E> {
private E data;
private Node<E> next;
public Node(E data) {
this.data = data;
}
}
}
测试
package com.collection;
public class Main {
public static void main(String[] args) {
LinkedQueue<String> queue = new LinkedQueue<>();
queue.offer("A");
queue.offer("B");
queue.offer("C");
queue.offer("D");
System.out.println(queue.peek());
while (!queue.isEmpty()) {
System.out.println(queue.poll());
}
}
}