java队列的实现

队列也可以通过数组和链表两种方式来实现。

 1、链表方式实现

 1 class Node{
 2     Node next = null;
 3     int data;
 4     public Node(int data){this.data = data;}
 5 }
 6 
 7 public class MyQueue<E>{
 8     private Node<E> head = null;
 9     private Node<E> tail = null;
10 
11     public boolean isEmpty(){
12         return head == tail;
13     }
14 
15     public void put(E data){
16         Node<E> newNode = new Node<E>(data);
17         if(head==null && tail==null){//队列为空
18             head = newNode;
19             tail = newNode;
20         }
21         else {
22             tail.next = newNode;
23             tail = newNode;
24         }
25     }
26 
27     public E pop(){
28         if(this.isEmpty())
29             return null;
30         E data = head.data;
31         head = head.next;
32         return data;
33     }
34 
35     public int size(){
36         Node<E> tmp = head;
37         int n = 0;
38         while (tmp!=null) {
39             n++;
40             tmp = tmp.next;
41         }
42         return n;
43     }
44 }

 2、list方式实现

 1 public class MyQueue<E>{
 2     private Linkedlist<E> list = new Linkedlist<E>();
 3     private int size = 0;
 4     public synchronized void put(E e){
 5         list.addLast(e);
 6         size++;
 7     }
 8 
 9     public synchronized E pop(){
10         size--;
11         return list.removeFrist();
12     }
13 
14     public synchronized boolean empty(){
15         return size == 0;
16     }
17 
18     public synchronized int size(){
19         return size;
20     }
21 }
原文地址:https://www.cnblogs.com/Eason-S/p/5505837.html