arduino 创建一个队列
在 Arduino 上创建一个队列可以使用数组和指针来实现。下面是一个简单的示例代码:
#define QUEUE_SIZE 10
int queue[QUEUE_SIZE];
int front = 0;
int rear = -1;
int itemCount = 0;
void enqueue(int data) {
if (itemCount >= QUEUE_SIZE) {
Serial.println("队列已满,无法添加新元素!");
return;
}
if (rear == QUEUE_SIZE - 1) {
rear = -1;
}
queue[++rear] = data;
itemCount++;
}
int dequeue() {
if (itemCount <= 0) {
Serial.println("队列为空,无法删除元素!");
return -1;
}
int data = queue[front++];
if (front == QUEUE_SIZE) {
front = 0;
}
itemCount--;
return data;
}
void setup() {
Serial.begin(9600);
enqueue(10);
enqueue(20);
enqueue(30);
Serial.println(dequeue()); // 输出 10
Serial.println(dequeue()); // 输出 20
Serial.println(dequeue()); // 输出 30
}
void loop() {
// 不需要在循环中做任何事情
}
这个示例代码创建了一个大小为 10 的队列,并实现了 enqueue() 和 dequeue() 函数来添加和删除元素。当队列已满时,enqueue() 函数会输出错误信息,并且不会添加新的元素。当队列为空时,dequeue() 函数会输出错误信息,并且返回 -1。
在 setup() 函数中,我们使用 enqueue() 函数向队列中添加了三个元素,并使用 dequeue() 函数逐个删除并输出元素。你可以根据需要修改这些函数来适应你的项目
原文地址: https://www.cveoy.top/t/topic/h5hh 著作权归作者所有。请勿转载和采集!