java 链表实现队列

  • Post author:
  • Post category:java


//链表节点
public class Node {
    Node next = null;
    int data;

    public Node(int data) {
        this.data = data;
    }
}

public class MyQueue<E> {
    Node head = null;//队列头
    Node tail = null;//队列尾


    /**
     * 插入队列
     * @param data
     */
    public  void  put(Integer data){
        Node newNode = new Node(data);
        if (head==null&&tail ==null){
            head = newNode;
            tail = newNode;
        }else {
            tail.next=newNode;
            tail =newNode;
        }
    }

    /**
     * 判断队列是否为空
     * @return
     */
    public Boolean isEmpty(){
        return head==tail;
    }

    /**
     * 出队列
     * @return
     */
    public Integer pop(){
        if (this.isEmpty()){
            return null;
        }
        int data = head.data;
        head=head.next;
        return data;
    }

    public int size(){
        int count = 0;
        Node tmp = head;
        while(tmp!=null){
            count++;
            tmp=tmp.next;
        }
        return count;
    }
}

public class TestQueue {
    public static <E> void main(String[] args) {
        MyQueue myQueue=new MyQueue();
        myQueue.put(1);
        myQueue.put(2);
        myQueue.put(3);
        Integer pop = myQueue.pop();
        System.out.println("pop="+pop);

        System.out.println(myQueue.size());
       



    }
}



版权声明:本文为qq_43791846原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。