Java数据结构之——队列:通过链表和数组实现

//链表实现队列

class Node<E>{
    Node<E> next = null;
    E data;
    public Node(E data){
        this.data = data;
    }
}
    public class ListQueue<E>{
        private Node<E> head = null;
        private Node<E> tail = null;
        public boolean empty(){
            return head==null;
        }
        
        public void put(E data){
            Node<E> newNode = new Node<E> (data);
            if(head == null && tail == null){
                head = tail = newNode;
                
            }
            else{
                tail.next = newNode;
                tail = tail.next;
            }
        }
        
        public E pop(){
            if(this.empty()){
                return null;
            }
            E data = head.data;
            head = head.next;
            return data;
        }
        
        public int size(){
            Node<E> tmp = head;
            int n = 0;
            while(tmp != null){
                n++;
                tmp = tmp.next;
            }
            return n;
        }
        
        public static void main(String[] args){
            ListQueue<Integer> q = new ListQueue<Integer>();
            q.put(2);
            q.put(5);
            q.put(6);
            System.out.println("The length:" + q.size());
            System.out.println("The first element:"+ q.pop());
        }
    }

下面介绍数组实现队列的方式,为了实现多线程安全,增加了对队列操作的同步。

//数组实现队列
import java.util.LinkedList;
public class ArrayQueue<E>{
    private LinkedList<E> list = new LinkedList<E>();
    private int size = 0;
    public synchronized void put(E e){
        list.addLast(e);
        size++;
    }
    
    public synchronized E pop(){
        size--;
        return list.removeFirst();
    }
    
    public synchronized boolean empty(){
        return size==0;
        
    }
    
    public synchronized int size(){
        return size;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_26552071/article/details/86412921