053. 使用指针和数组实现队列
在C语言中,队列是一种先进先出(FIFO)的数据结构。使用指针和数组实现队列是一种常见的方法。队列的基本操作包括入队(enqueue
)、出队(dequeue
)、查看队首元素(peek
)以及判断队列是否为空(isEmpty
)。
C语言实现队列的方法
数组实现
使用数组实现队列是最简单的方式。需要维护两个指针,一个指向队列的头部(front),另一个指向队列的尾部(rear)。当元素入队时,rear指针向后移动;当元素出队时,front指针向后移动。需要注意的是,数组实现的队列可能会遇到“假溢出”问题,即数组未满但无法继续插入元素。
#define MAX_SIZE 100
int queue[MAX_SIZE];
int front = -1, rear = -1;
void enqueue(int value) {
if (rear == MAX_SIZE - 1) {
printf("Queue is full\n");
} else {
if (front == -1) front = 0;
rear++;
queue[rear] = value;
}
}
int dequeue() {
if (front == -1 || front > rear) {
printf("Queue is empty\n");
return -1;
} else {
int value = queue[front];
front++;
return value;
}
}
链表实现
使用链表实现队列可以避免数组实现中的“假溢出”问题。链表实现的队列需要维护两个指针,一个指向链表的头部(front),另一个指向链表的尾部(rear)。入队操作在链表尾部插入节点,出队操作在链表头部删除节点。
struct Node {
int data;
struct Node* next;
};
struct Node* front = NULL;
struct Node* rear = NULL;
void enqueue(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;
if (rear == NULL) {
front = rear = newNode;
} else {
rear->next = newNode;
rear = newNode;
}
}
int dequeue() {
if (front == NULL) {
printf("Queue is empty\n");
return -1;
} else {
</