zoukankan      html  css  js  c++  java
  • 数据结构学习(五) Java链表实现队列

    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();
        }
    }
    

      

  • 相关阅读:
    RTOS双向链表数据结构
    [LintCode] Majority Number(以时间复杂度O(n)求主元素)
    [LintCode] Median(期望时间复杂度O(n)求中位数和第k大数)
    [LintCode]unique paths with obstacles
    [LintCode]unique paths
    [LintCode]sqrt(x)
    排序算法(C++实现)
    优先队列C++实现
    散列之分离链接法
    AVL树C++实现
  • 原文地址:https://www.cnblogs.com/412013cl/p/11008499.html
Copyright © 2011-2022 走看看