实现队列的①创建、②入队、③出队、④取队首元素、⑤判断队列是否为空 队列中的元素可以是学号与姓名 编写程序主函数,对各个功能函数进行调用 顺序存储c语言
时间: 2024-06-06 10:11:00 浏览: 59
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAXSIZE 100
typedef struct {
char id[10]; // 学号
char name[20]; // 姓名
} Element;
typedef struct {
Element data[MAXSIZE];
int front; // 队首指针
int rear; // 队尾指针
} Queue;
void createQueue(Queue *q) {
q->front = q->rear = -1;
}
int isEmpty(Queue q) {
if (q.front == q.rear) {
return 1;
} else {
return 0;
}
}
int isFull(Queue q) {
if (q.rear == MAXSIZE - 1) {
return 1;
} else {
return 0;
}
}
void enqueue(Queue *q, Element e) {
if (isFull(*q)) {
printf("Queue is full!\n");
return;
} else {
q->rear++;
q->data[q->rear] = e;
}
}
Element dequeue(Queue *q) {
if (isEmpty(*q)) {
printf("Queue is empty!\n");
Element e = {"", ""};
return e;
} else {
q->front++;
return q->data[q->front];
}
}
Element getFront(Queue q) {
if (isEmpty(q)) {
printf("Queue is empty!\n");
Element e = {"", ""};
return e;
} else {
return q.data[q.front + 1];
}
}
int main() {
Queue q;
createQueue(&q);
Element e1 = {"001", "Tom"};
Element e2 = {"002", "Jack"};
Element e3 = {"003", "Lucy"};
enqueue(&q, e1);
enqueue(&q, e2);
enqueue(&q, e3);
printf("Queue front: %s %s\n", getFront(q).id, getFront(q).name);
while (!isEmpty(q)) {
Element e = dequeue(&q);
printf("Dequeue: %s %s\n", e.id, e.name);
}
return 0;
}
阅读全文