在C語言中,實現隊列這種數據結構,可以使用數組或鏈表。以下是使用這兩種數據結構實現隊列的示例:
方法一:使用數組
#include <stdio.h>
#include <stdlib.h>
#define SIZE 5
typedef struct {
int data[SIZE];
int front;
int rear;
} Queue;
Queue q;
void initQueue() {
q.front = q.rear = -1;
}
int isFull() {
return (q.rear + 1) % SIZE == q.front;
}
int isEmpty() {
return q.front == -1;
}
void enqueue(int item) {
if (isFull()) {
printf("Queue is full.\n");
return;
}
if (isEmpty()) {
q.front = q.rear = 0;
} else {
q.rear = (q.rear + 1) % SIZE;
}
q.data[q.rear] = item;
}
int dequeue() {
if (isEmpty()) {
printf("Queue is empty.\n");
return -1;
}
int item = q.data[q.front];
if (q.front == q.rear) {
q.front = q.rear = -1;
} else {
q.front = (q.front + 1) % SIZE;
}
return item;
}
int main() {
initQueue();
enqueue(1);
enqueue(2);
enqueue(3);
printf("Dequeued: %d\n", dequeue());
printf("Dequeued: %d\n", dequeue());
return 0;
}
方法二:使用鏈表
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
typedef struct {
Node* front;
Node* rear;
} Queue;
Queue* createQueue() {
Queue* q = (Queue*)malloc(sizeof(Queue));
q->front = q->rear = NULL;
return q;
}
void initQueue(Queue* q) {
q->front = q->rear = NULL;
}
int isFull(Queue* q) {
return q->rear->next == NULL;
}
int isEmpty(Queue* q) {
return q->front == NULL;
}
void enqueue(Queue* q, int item) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = item;
newNode->next = NULL;
if (isFull(q)) {
printf("Queue is full.\n");
return;
}
if (isEmpty(q)) {
q->front = q->rear = newNode;
} else {
q->rear->next = newNode;
q->rear = newNode;
}
}
int dequeue(Queue* q) {
if (isEmpty(q)) {
printf("Queue is empty.\n");
return -1;
}
Node* temp = q->front;
int item = temp->data;
q->front = q->front->next;
if (q->front == NULL) {
q->rear = NULL;
}
free(temp);
return item;
}
int main() {
Queue* q = createQueue();
initQueue(q);
enqueue(q, 1);
enqueue(q, 2);
enqueue(q, 3);
printf("Dequeued: %d\n", dequeue(q));
printf("Dequeued: %d\n", dequeue(q));
return 0;
}
這兩種方法都可以實現隊列的基本操作,包括入隊(enqueue)和出隊(dequeue)。你可以根據自己的需求和場景選擇合適的方法。