Java实现队列

队列定义

队列:队列是只允许在一端进行插入操作,而在另一端进行删除操作.
队列是一种先进先出(FIFO)的线性表,允许插入的一端称为队尾,允许删除的一端称为队头.

队列操作

入队:向队尾添加元素;
出队:获取并移除队头元素;
这里写图片描述

链式队列实现

创建节点

data:节点数据
next:指向下一个节点

class Node{     
    public Integer data;
    public Node next;
    public Node(Integer data) {
        super();
        this.data = data;
    }
}

创建队列

class Queue{    
 //头节点
    private Node front;
    //尾节点
    private Node rear;
    //数据量
    private Integer size = 0;
}

入队操作

    public void enQueue(Integer data) {
        Node n = new Node(data);

        if(front == null) {
            front = n;
            rear = front;
        }
        else {
            rear.next = n;
            //非循环队列
            rear = n;

            //循环队列
            //rear.next = front
        }
        size++;
    }

出队操作

    public Integer deQueue(){

        if(front == null) {
            return front.data;
        }
        else {
            Integer data = front.data;
            Node fNode = front;
            front = fNode.next;
            //将头节点指向null,等待垃圾回收器回收
            fNode = null;
            size--;
            return data;
        }

    }

清空队列

    public void clean() {
        Node fNode  = front;
        while(fNode != null) {
            front = fNode.next;
            fNode = null;
            fNode = front;
            size--;
        }
        rear = null;
    }
    public String toString() {
        String str = "The Queue data is : ";
        Node fNode  = front;
        while(fNode != null) {
            str += fNode.data + "  ";
            fNode  = fNode.next;
        }
        str += "\t" + "the size is :" + size;
        return str;
    }
}

测试

public static void main(String[] args) {
        // TODO Auto-generated method stub
        Queue queue = new Queue();

        System.out.println("队列插入操作");
        queue.enQueue(20);
        queue.enQueue(15);
        queue.enQueue(10);
        queue.enQueue(5);

        System.out.println(queue.toString());
        System.out.println("队列获取元素");
        Integer data = queue.deQueue();
        System.out.println("获取的元素为:" + data);
        System.out.println(queue.toString());

        System.out.println("队列清空元素");
        queue.clean();
        System.out.println(queue.toString());

    }

输出

队列插入操作
The Queue data is : 20  15  10  5   the size is :4
队列获取元素
获取的元素为:20
The Queue data is : 15  10  5   the size is :3
队列清空元素
The Queue data is :     the size is :0
  • 0
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值