java数据结构之队列(使用头尾节点实现)

/**
 * 对于链表的实现,如果只对连标头进行操作,则是O(1)的时间复杂度
 * 如果对链表尾进行操作则是O(n)的时间复杂度
 *而在用数组实现的队列同样出现了此类问题,所以解决这类问题的方式是使用循环队列
 *而对于链表而言则是使用尾指针
 *出于性能的考虑
 */

public class LinkedQueue2<E> {
    //对队列进行操作时不再使用虚拟头结点
    //因为不涉及对中间元素的操作
    private class Node{
        public E e ;
        public Node next ;
        
        public Node(E e , Node next) {
            this.e = e ;
            this.next = next ;
        }
        
        public Node(E e) {
            this(e, null) ;
         }
        
        public Node() {
            this(null, null) ;
        }
        
        @Override
        public String toString() {
            return e.toString() ;
        }
    }
    
    private Node head , tail ;
    private int size ;
    public boolean isEmpty() {
        return size == 0 ;
    }
    
    public int getSize() {
        return size ; 
    }
    public LinkedQueue2() {
        head = null ;
        tail = null ;
        size = 0 ;
    }
    
    public E search() {
        return head.e ;
    }
    public void enqueue(E e) {
        Node node = new Node(e) ;
        if(tail == null) {
            tail = node ;
            head = node ;
        } else {
            tail.next = node ;
            tail = tail.next ;
        }
        size ++ ;
    }
    
    public E dequeue() {
        Node node ;
        if(size == 0) {
            throw new IllegalArgumentException("NULL Exception");
        }
        if(size == 1) {
            node = head ;
            tail = null ; 
            head = null ;

        } else {
            node = head ;
            head = head.next ;

        }
        size -- ;
        return node.e ;
    }
    
    public static void main(String[] args) {
        LinkedQueue2<Integer> list = new LinkedQueue2<>() ;
        list.enqueue(15);
        list.enqueue(38);
        list.enqueue(55);
        System.out.print("队列的大小:");
        System.out.println(list.getSize());
        System.out.print("队列的第一个元素:");        
        System.out.println(list.search());
        System.out.print("队列出队:");
        System.out.println(list.dequeue());
        System.out.print("出队后队列的大小:");
        System.out.println(list.getSize());
        System.out.print("再次查看此时队列的元素:");
        System.out.println(list.search());
    }
}

猜你喜欢

转载自blog.csdn.net/sxapple666/article/details/88621766