基于鏈表實(shí)現(xiàn)的隊(duì)列
時(shí)間復(fù)雜度:
入隊(duì):O(1)
出隊(duì):O(1)
接口類:
public interface Queue<E> {
void enqueue(E e);
E dequeue();
E getFront();
int getSize();
boolean isEmpty();
}
實(shí)現(xiàn)類
public class LinkedListQueue<E> implements Queue<E> {
//結(jié)點(diǎn)類
class Node{
public Node next;
public E e ;
public Node(E e,Node next){
this.e = e;
this.next = next;
}
public Node(E e){
this(e,null);
}
public Node(){
this(null,null);
}
}
private Node head;//頭結(jié)點(diǎn)
private Node tail;//尾結(jié)點(diǎn)
private int size;
//初始化
public LinkedListQueue(){
head = null;
tail = null;
size = 0;
}
@Override
public void enqueue(E e) {
//隊(duì)空
if (tail == null){
Node node = new Node(e);
tail = node;
head = tail;
}
else {
Node node = new Node(e);
tail.next = node;
tail = tail.next;
}
size++;
}
@Override
public E dequeue() {
if (isEmpty()){
throw new IllegalArgumentException("隊(duì)列為空焚虱,無(wú)法刪除元素");
}
Node reNode = head;
head = head.next;
reNode.next = null;
//刪除后隊(duì)空了
if (head == null){
tail =null;
}
size--;
return reNode.e;
}
@Override
public E getFront() {
if (isEmpty()){
throw new IllegalArgumentException("隊(duì)列為空");
}
return head.e;
}
@Override
public int getSize() {
return size;
}
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public String toString() {
StringBuilder res = new StringBuilder();
res.append("LinkedListQueue: front");
Node cur = head;
while (cur != null){
res.append(cur.e + "->");
cur = cur.next;
}
res.append("NULL tail");
return res.toString();
}
}
測(cè)試:
public class Main {
public static void main(String[] args) {
Queue<Integer> queue = new LinkedListQueue<>();
for (int i = 0 ; i < 9 ; i ++){
queue.enqueue(i);
System.out.println(queue);
}
for (int i = 0 ; i < 5 ; i++)
queue.dequeue();
System.out.println(queue);
for (int i = 0 ; i < 5 ; i ++){
queue.enqueue(i);
}
System.out.println(queue);
System.out.println(queue.getFront());
System.out.println(queue.getSize());
}
}