程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

队列(Queue)

发布于2021-03-13 14:12     阅读(911)     评论(0)     点赞(17)     收藏(4)


概念:

只允许在一端进行数据插入操作,再另一端进行删除数据的特殊线性表,具有先进先出(FIFO)特性,进行插入的一端称为队尾,进行删除操作的一端称为对头。

基本方法:

1.E offer(); 入队
2.E poll(); 出队
3.E peek(); 查看队首元素(不删除)

实现:(以int类型数据为例)

class Node{
    public int val;
    public Node next;

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


}

public class MyQueue {
    public Node first;//头
    public Node last;//尾
    public int size;


    public boolean offer(int val){
        Node node = new Node(val);
        if(this.first == null){
            this.first = node;
            this.last = node;
        }else{
            this.last.next = node;
            this.last = node;
        }
        size++;
        return true;
    }


    public int poll() throws RuntimeException{
        if(isEmpty()){
            throw new RuntimeException("队列为空!");
        }
        int ret = this.first.val;
        this.first = this.first.next;
        size--;
        return ret;
    }

    public int peek()  throws RuntimeException{
        if(isEmpty()){
            throw new RuntimeException("队列为空!");
        }
        return this.first.val;
    }

    public boolean isEmpty(){
        if(this.first == null && this.last == null){
            return true;
        }
        return false;
    }

    public void show(){
        for(int i = 0; i < size; i++){
            System.out.println(this.first.val);
            this.first = this.first.next;
        }
    }
    public static void main(String[] args) {
        MyQueue myQueue = new MyQueue();
        myQueue.offer(5);
        myQueue.offer(9);
        myQueue.offer(3);
//        System.out.println(myQueue.peek());
//        myQueue.poll();
//        System.out.println(myQueue.size);
        myQueue.show();
    }
}

原文链接:https://blog.csdn.net/DavenportChen/article/details/114675027



所属网站分类: 技术文章 > 博客

作者:欧美丽

链接:http://www.javaheidong.com/blog/article/114324/f758c7934abc4d28cce3/

来源:java黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

17 0
收藏该文
已收藏

评论内容:(最多支持255个字符)