数据结构及算法之队列(基于链表)讲解

1,具体实现

package com.dream21th.algorithmicdatastructure.linkedlist;

/**
 * @Auther: hp
 * @Date: 2019/9/13 20:52
 * @Description:
 */
public class LinkedListQueue implements Queue {

    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;
    private Node tail;
    private int size;

    public LinkedListQueue(){
        head=null;
        tail=null;
        size=0;
    }
    @Override
    public int getSize() {
        return size;
    }

    @Override
    public void enquene(E e) {

        if(tail==null){
            tail=new Node(e);
            head=tail;
        }else {
            tail.next=new Node(e);
            tail=tail.next;
        }
        size++;
    }

    @Override
    public E dequene() {
        if(isEmpty()){
            throw new IllegalArgumentException("illeage operator");
        }
        Node current = this.head;
        head=head.next;
        current.next=null;
        if(head==null){
            tail=null;
        }
        size--;
        return current.e;
    }

    @Override
    public E getfornt() {
        if(isEmpty()){
            throw new IllegalArgumentException("illeage operator");
        }
        return head.e;
    }

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

    @Override
    public String toString() {

        StringBuilder builder=new StringBuilder();

        builder.append("Queue head");
        builder.append("[");

        for(Node cur=head;cur!=null;cur=cur.next){
            builder.append(cur+"->");
        }
        builder.append("Null ] tail");
        return builder.toString();
    }

    public static void main(String[] args) {
        LinkedListQueue linkedListStack = new LinkedListQueue<>();

        for(int i=0;i<10;i++){
            linkedListStack.enquene(i);
        }
        linkedListStack.dequene();
        linkedListStack.dequene();
        System.out.println(linkedListStack);
    }
}

 

你可能感兴趣的:(数据结构与算法)