双向链表实现队列
public class LinkedListQueue<E> implements Queue<E>{ 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(null,null); } public String toString (){ return e.toString(); } } Node head; Node tail; int size; //初始化链表 public LinkedListQueue(){ head = null; tail = null; size=0; } @Override public int getSize() { return size; } @Override public boolean isEmpty() { return size==0; } @Override public void enqueue(E e) { Node node = new Node(e); if(size==0){ head = tail = node; size++; }else{ tail.next = node; tail = tail.next; size++; } } @Override public void enQueue(Object e) { } @Override public E deQueue() { if(isEmpty()){ throw new IllegalArgumentException("空数组不能进行操作"); }else { Node pre=head; Node ret = head.next; head = ret; size--; return pre.e; } } @Override public E getFront() { if(isEmpty()){ throw new IllegalArgumentException("空数组不能进行操作"); }else { return head.e; } } public String toString (){ StringBuilder str = new StringBuilder(); str.append("front"); str.append("["); // Node node = head; // while(node!=null){ // str.append(node +"->"); // node = node.next; // } //两种遍历方式、 for(Node node = head;node!=null;node = node.next){ str.append(node +"->"); } str.append("NULL"); str.append("]"); str.append("tail"); return str.toString(); } public static void main(String[] args){ LinkedListQueue<Integer> LL = new LinkedListQueue<>(); for (int i = 0; i < 10; i++) { LL.enqueue(i); } System.out.println(LL.size); System.out.println(LL); for(int i=0;i<5;i++) { System.out.println("出栈:"+LL.deQueue()); System.out.println(LL); } } }
运行通过