package queue; /** * @Title: LinkedListQueue * @ProjectName demo */ public class LinkedListQueue<E> implements Queue<E> { private class Node { private Node next; private E e; public Node(E e, Node next) { this.next = next; this.e = e; } public Node(E e) { this(e, null); } @Override public String toString() { return e.toString(); } } private int size; private Node head, tail; public LinkedListQueue() { size = 0; head = null; tail = null; } @Override public int getSize() { return size; } @Override public boolean isEmpty() { return size == 0; } @Override public void enqueue(E e) { if (tail == null) { tail = new Node(e); head = tail; }else{ tail.next = new Node(e); tail = tail.next; } size ++; } @Override public E dequeue() { if (isEmpty()){ throw new IllegalArgumentException("dequeue error.."); } Node cur = head; head = head.next; cur.next = null; if (head == null){ tail = null; } size--; return cur.e; } @Override public E getFront() { if (isEmpty()){ throw new IllegalArgumentException("GetFront error.."); } return head.e; } @Override public String toString() { StringBuilder sb = new StringBuilder("front:"); Node h = head; while (h != null) { sb.append("--->"+h.e); h = h.next; } sb.append("tail"); return sb.toString(); } }