含泪总结篇:数据结构—队列
数据结构—队列
系列文章
队列
-
概念:是一种 “操作受限” 的线性表。在队头(表头)删除操作,在队尾(表位)插入操作 特点: 先进现出出,后进后出 只有两种操作,入队(队尾插入)和出队(队头删除) 优势:数组或链表暴露了太多的操作接口,不适合特点的场景下的安全和可控情况。
顺序队列
-
顺序队列是用数组实现的队列
代码实现
// 用数组实现的队列 public class ArrayQueue { // 数组:items,数组大小:n private String[] items; private int n = 0; // head 表示队头下标,tail 表示队尾下标 private int head = 0; private int tail = 0; // 申请一个大小为 capacity 的数组 public ArrayQueue(int capacity) { items = new String[capacity]; n = capacity; } // 入队操作,将 item 放入队尾 public boolean enqueue(String item) { // tail == n 表示队列末尾没有空间了 if (tail == n) { // tail ==n && head==0,表示整个队列都占满了 if (head == 0) return false; // 数据搬移 for (int i = head; i < tail; ++i) { items[i-head] = items[i]; } // 搬移完之后重新更新 head 和 tail tail -= head; head = 0; } items[tail] = item; ++tail; return true; } // 出队 public String dequeue() { // 如果 head == tail 表示队列为空 if (head == tail) return null; // 为了让其他语言的同学看的更加明确,把 -- 操作放到单独一行来写了 String ret = items[head]; ++head; return ret; } }
链式队列
-
链式队列是用链表实现的队列
代码实现
/** * 基于链表实现的队列 * * Author: Zheng */ public class QueueBasedOnLinkedList { // 队列的队首和队尾 private Node head = null; private Node tail = null; // 入队 public void enqueue(String value) { if (tail == null) { Node newNode = new Node(value, null); head = newNode; tail = newNode; } else { tail.next = new Node(value, null); tail = tail.next; } } // 出队 public String dequeue() { if (head == null) return null; String value = head.data; head = head.next; if (head == null) { tail = null; } return value; } public void printAll() { Node p = head; while (p != null) { System.out.print(p.data + " "); p = p.next; } System.out.println(); } private static class Node { private String data; private Node next; public Node(String data, Node next) { this.data = data; this.next = next; } public String getData() { return data; } } }
循环队列
并发队列
阻塞队列
灵魂三问:
-
有没有觉得技术得不到系统的提升,技术成长慢? 有没面试懵逼,升职加薪难? 有没有想过去大一点的世界看看?
重要的事情说三遍:
-
学习、挣钱、自由 学习、挣钱、自由 学习、挣钱、自由
疫情当下,唯有自强
下一篇:
链表之合并两个排序的链表