用C语言设计菜单定义存储整数的循环队列和链队列,编写初始化/创建、入队和出队操作的算法
时间: 2024-02-25 11:58:05 浏览: 23
好的,我会根据您的要求,为您回答这个问题。
首先是循环队列的算法:
1.定义循环队列的结构体
```
#define QUEUE_SIZE 5 // 队列的大小
typedef struct {
int data[QUEUE_SIZE];
int front; // 队头指针
int rear; // 队尾指针
} SeqQueue;
```
2.初始化队列
```
void InitQueue(SeqQueue *Q) {
Q->front = Q->rear = 0;
}
```
3.入队操作
```
int EnQueue(SeqQueue *Q, int x) {
if ((Q->rear + 1) % QUEUE_SIZE == Q->front) {
return 0; // 队列已满
}
Q->data[Q->rear] = x;
Q->rear = (Q->rear + 1) % QUEUE_SIZE;
return 1;
}
```
4.出队操作
```
int DeQueue(SeqQueue *Q, int *x) {
if (Q->front == Q->rear) {
return 0; // 队列已空
}
*x = Q->data[Q->front];
Q->front = (Q->front + 1) % QUEUE_SIZE;
return 1;
}
```
接下来是链队列的算法:
1.定义链队列的结构体
```
typedef struct qnode {
int data;
struct qnode *next;
} QNode;
typedef struct {
QNode *front;
QNode *rear;
} LinkQueue;
```
2.初始化队列
```
void InitQueue(LinkQueue *Q) {
Q->front = Q->rear = (QNode *)malloc(sizeof(QNode));
Q->front->next = NULL;
}
```
3.入队操作
```
int EnQueue(LinkQueue *Q, int x) {
QNode *p = (QNode *)malloc(sizeof(QNode));
if (p == NULL) {
return 0; // 内存分配失败
}
p->data = x;
p->next = NULL;
Q->rear->next = p;
Q->rear = p;
return 1;
}
```
4.出队操作
```
int DeQueue(LinkQueue *Q, int *x) {
if (Q->front == Q->rear) {
return 0; // 队列已空
}
QNode *p = Q->front->next;
*x = p->data;
Q->front->next = p->next;
if (Q->rear == p) {
Q->rear = Q->front;
}
free(p);
return 1;
}
```
以上就是用 C 语言设计菜单定义存储整数的循环队列和链队列,编写初始化/创建、入队和出队操作的算法。希望对您有所帮助。