算法导论10.1队列
注意n个空间的队列,有最多n - 1个元素
1 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 | /* * IA_10.1queue.h * * Created on: Feb 13, 2015 * Author: sunyj */ #ifndef IA_10_1QUEUE_H_ #define IA_10_1QUEUE_H_ #include <iostream> #include <cstdint> // ENQUEUE(Q, x) // Q[Q.tail] = x // if Q.tail = Q.length // Q.tail = 1 // else Q.tail = Q.tail + 1 // DEQUEUE(Q) // x = Q[Q.haed] // if Q.head == Q.length // Q.head = 1 // Q.head = Q.head + 1 // return x template < class T> class queue { public : queue(int64_t const n) : head(0), tail(0), length(n) { data = new T[n](); } bool full() { if (head == tail + 1 || (0 == head && length == tail + 1)) { return true ; } return false ; } bool empty() { return head == tail; } void print() { if (empty()) { return ; } if (head < tail) { for (int64_t i = head; i < tail; i++) { std::cout << data[i] << " " ; } } else { for (int64_t i = head; i < length; i++) { std::cout << data[i] << " " ; } for (int64_t i = 0; i < tail; i++) { std::cout << data[i] << " " ; } } std::cout << std::endl; return ; } int64_t enqueue(T const x) { if (full()) { std::cout << "queue is full, enqueue failed" << std::endl; return -1; } data[tail] = x; if (length == tail + 1) { tail = 0; } else { ++tail; } return 0; } int64_t dequeue(T& x) { if (empty()) { return -1; } x = data[head]; if (length - 1 == head) { head = 0; } else { ++head; } return 0; } void clear() { while (!empty()) { T x; dequeue(x); } } private : int head; // points to the first element of the queue, the element has already been in queue int tail; // points to the next coming element T* data; int64_t const length; // the queue can hold at most length-1 element }; #endif /* IA_10_1QUEUE_H_ */ |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | /* * IA_10.1queue.cpp * * Created on: Feb 11, 2015 * Author: sunyj */ #include "IA_10.1queue.h" int main() { queue< int > q(4); q.enqueue(1); q.enqueue(2); q.enqueue(3); // after enqueue 3, the queue is full q.enqueue(4); // enqueue failed, because the queue is full q.print(); int x; if (0 == q.dequeue(x)) { std::cout << x << std::endl; } if (0 == q.dequeue(x)) { std::cout << x << std::endl; } q.print(); q.enqueue(4); q.enqueue(5); q.enqueue(6); // enqueue failed, because the queue is full q.print(); // elements 3, 4, 5 q.clear(); q.print(); return 0; } |
1 | |
1 | |
1 | |
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步