数据结构:队列

什么是队列:

队列与栈一样,也是一种线性表,不同的是,队列可以在一端添加元素,在另一端取出元素,也就是:先进先出。从一端放入元素的操作称为入队,取出元素为出队,

特点:

1 . 队列跟栈一样,也是一种抽象的数据结构。

  1. 具有先进先出的特性,支持在队尾插入元素,在队头删除元素。

实现:

队列可以用数组来实现,也可以用链表来实现。

用数组实现的队列叫作顺序队列,用链表实现的队列叫作链式队列。

复制代码
public class Queue<T> {
    //记录头结点
    private Node head;
    //记录尾节点
    private Node last;
    //记录元素个数
    private int N;

    public Queue() {  //初始化
        this.head = new Node(null,null);
        this.last = null;
        N=0;
    }

    //尾插法
    public void inQueue(T t){ //往队列插入元素
        if (last==null){ //插入第一个元素时
            last=new Node(t,null);
            head.next=last; //此时头尾节点指向同一个元素
            N++;
        }else {//不为空时
            Node temp=last;
            last=new Node(t,null);
            temp.next=last;

        }
        N++;
    }


    //拿元素  相当于头删元素
    public T outQueue(){
        if (head.next==null){
            return null;
        }else {
            Node first=head.next; //第一个元素
            head.next=first.next;
            N--;
            if (N==0){  //如果最后元素拿完 需要重置last 否则此时last依旧指向最后一个元素
                last=null;
            }
            return first.item;
        }
    }


    private class Node{
        private T item;
        private Node next;

        public Node(T t, Node next) {
            this.item = t;
            this.next = next;
        }
    }
}
相关推荐
田梓燊1 小时前
code 560
数据结构·算法·哈希算法
会编程的土豆2 小时前
【数据结构与算法】动态规划
数据结构·c++·算法·leetcode·代理模式
棉花骑士2 小时前
【AI Agent】面向 Java 工程师的Claude Code Harness 学习指南
java·开发语言
爱敲代码的小鱼3 小时前
springboot(2)从基础到项目创建:
java·spring boot·spring
迈巴赫车主3 小时前
蓝桥杯19724食堂
java·数据结构·算法·职场和发展·蓝桥杯
Kethy__4 小时前
计算机中级-数据库系统工程师-数据结构-查找算法
数据结构·算法·软考·查找算法·计算机中级
所以遗憾是什么呢?4 小时前
【题解】Codeforces Round 1081 (Div. 2)
数据结构·c++·算法·acm·icpc·ccpc·xcpc
i220818 Faiz Ul4 小时前
动漫商城|基于springboot + vue动漫商城系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·动漫商城系统
海兰4 小时前
【实战】MCP 服务在 Nacos 中注册状态分析与优化
android·java·github·银行系统·银行ai
OOJO5 小时前
c++---vector介绍
c语言·开发语言·数据结构·c++·算法·vim·visual studio