鏈表實現隊列LinkedQueue


/**
 * 使用鏈表實現隊列
 * @param <E>
 */
public class LinkedQueue<E> implements Queue<E> {

    public static void main(String[] a) {

        LinkedQueue<Integer> list = new LinkedQueue<>();


        for (int i = 0; i < 5; i++) {
            list.enqueue(i);
            System.out.println(list);
        }

        list.dequeue();
        System.out.println(list);



    }
    //隊首對象,隊尾對象
    Node head, tail;
    int size;


    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    //入隊
    @Override
    public void enqueue(E o) {
        //隊尾爲null,整個鏈表爲null
        if (tail == null) {
            tail = new Node(o);
            head = tail;
        } else {
            tail.next = new Node(o);
            tail = tail.next;

        }
        size++;

    }

    //出隊(移除隊首)
    @Override
    public E dequeue() {
        if (isEmpty())
            throw new IllegalArgumentException("list is null");

        Node ret = head;
        head = head.next;
        ret.next = null;
        if (head == null) {
            tail = null;
        }
        size--;
        return ret.e;
    }

    //獲取隊首
    @Override
    public E getFront() {
        if (isEmpty())
            throw new IllegalArgumentException("list is null");
        return head.e;
    }

    @NonNull
    @Override
    public String toString() {
        StringBuilder ret = new StringBuilder();
        ret.append("LinkedQueue ");
        ret.append("[");
        Node pre = head;
        for (int i = 0; i < size; i++) {

            ret.append("<---"+pre.e);
            pre = pre.next;

        }
        ret.append("]");
        return ret.toString();
    }

    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.e = null;
            this.next = null;
        }

        @Override
        public String toString() {
            return e.toString();
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章