在Linux中,队列通常是通过数据结构(如链表、数组等)来实现的
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
typedef struct Queue {
Node* front;
Node* rear;
int size;
} Queue;
Queue* createQueue(int capacity) {
Queue* queue = (Queue*)malloc(sizeof(Queue));
queue->front = NULL;
queue->rear = NULL;
queue->size = capacity;
return queue;
}
int isEmpty(Queue* queue) {
return (queue->front == NULL);
}
void enqueue(Queue* queue, int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (isEmpty(queue)) {
queue->front = newNode;
queue->rear = newNode;
} else {
queue->rear->next = newNode;
queue->rear = newNode;
}
queue->size++;
}
int dequeue(Queue* queue) {
if (isEmpty(queue)) {
printf("Queue is empty.\n");
return -1;
}
Node* temp = queue->front;
int data = temp->data;
queue->front = temp->next;
if (queue->front == NULL) {
queue->rear = NULL;
}
free(temp);
queue->size--;
return data;
}
void printQueue(Queue* queue) {
Node* temp = queue->front;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
int main() {
Queue* queue = createQueue(5);
enqueue(queue, 10);
enqueue(queue, 20);
enqueue(queue, 30);
printQueue(queue);
dequeue(queue);
printQueue(queue);
return 0;
}
这个示例展示了如何在C语言中创建一个简单的队列,并进行入队、出队和打印操作。你可以根据自己的需求对这个示例进行修改和扩展。