mirror of
https://github.com/krahets/hello-algo.git
synced 2025-07-06 22:34:18 +08:00
update stack and queue.
This commit is contained in:
@ -9,26 +9,27 @@
|
||||
/* 基于环形数组实现的队列 */
|
||||
class ArrayQueue {
|
||||
private:
|
||||
vector<int> nums; // 用于存储队列元素的数组
|
||||
int front = 0; // 头指针,指向队首
|
||||
int rear = 0; // 尾指针,指向队尾 + 1
|
||||
int *nums; // 用于存储队列元素的数组
|
||||
int cap; // 队列容量
|
||||
int front = 0; // 头指针,指向队首
|
||||
int rear = 0; // 尾指针,指向队尾 + 1
|
||||
|
||||
public:
|
||||
ArrayQueue(int capacity) {
|
||||
// 初始化数组
|
||||
nums.resize(capacity);
|
||||
cap = capacity;
|
||||
nums = new int[capacity];
|
||||
}
|
||||
|
||||
/* 获取队列的容量 */
|
||||
int capacity() {
|
||||
return nums.size();
|
||||
return cap;
|
||||
}
|
||||
|
||||
/* 获取队列的长度 */
|
||||
int size() {
|
||||
int cap = capacity();
|
||||
// 由于将数组看作为环形,可能 rear < front ,因此需要取余数
|
||||
return (cap + rear - front) % cap;
|
||||
return (capacity() + rear - front) % capacity();
|
||||
}
|
||||
|
||||
/* 判断队列是否为空 */
|
||||
@ -67,6 +68,14 @@ public:
|
||||
return nums[front];
|
||||
}
|
||||
|
||||
/* 访问指定索引元素 */
|
||||
int get(int index) {
|
||||
if (index >= size())
|
||||
throw out_of_range("索引越界");
|
||||
return nums[(front + index) % capacity()];
|
||||
}
|
||||
|
||||
/* 将数组转化为 Vector 并返回 */
|
||||
vector<int> toVector() {
|
||||
int siz = size();
|
||||
int cap = capacity();
|
||||
@ -99,6 +108,10 @@ int main() {
|
||||
int peek = queue->peek();
|
||||
cout << "队首元素 peek = " << peek << endl;
|
||||
|
||||
/* 访问指定索引元素 */
|
||||
int num = queue->get(2);
|
||||
cout << "队列第 3 个元素为 num = " << num << endl;
|
||||
|
||||
/* 元素出队 */
|
||||
int poll = queue->poll();
|
||||
cout << "出队元素 poll = " << poll << ",出队后 queue = ";
|
||||
|
Reference in New Issue
Block a user