用C++ 实现顺序队列、链式队列的建立、进队、出队、返回队头元素、输出算法。
时间: 2023-10-03 19:08:33 浏览: 136
顺序队列代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef struct {
int data[MAXSIZE];
int front, rear;
} SeqQueue;
void initQueue(SeqQueue *q) {
q->front = q->rear = 0;
}
int isQueueEmpty(SeqQueue *q) {
return q->front == q->rear;
}
int isQueueFull(SeqQueue *q) {
return (q->rear + 1) % MAXSIZE == q->front;
}
int enQueue(SeqQueue *q, int x) {
if (isQueueFull(q)) {
printf("Queue is full!\n");
return 0;
}
q->data[q->rear] = x;
q->rear = (q->rear + 1) % MAXSIZE;
return 1;
}
int deQueue(SeqQueue *q, int *x) {
if (isQueueEmpty(q)) {
printf("Queue is empty!\n");
return 0;
}
*x = q->data[q->front];
q->front = (q->front + 1) % MAXSIZE;
return 1;
}
int getHead(SeqQueue *q, int *x) {
if (isQueueEmpty(q)) {
printf("Queue is empty!\n");
return 0;
}
*x = q->data[q->front];
return 1;
}
void printQueue(SeqQueue *q) {
if (isQueueEmpty(q)) {
printf("Queue is empty!\n");
return;
}
printf("Queue: ");
int i = q->front;
while (i != q->rear) {
printf("%d ", q->data[i]);
i = (i + 1) % MAXSIZE;
}
printf("\n");
}
int main() {
SeqQueue q;
initQueue(&q);
enQueue(&q, 1);
enQueue(&q, 2);
enQueue(&q, 3);
printQueue(&q);
int x;
deQueue(&q, &x);
printf("Dequeue: %d\n", x);
printQueue(&q);
getHead(&q, &x);
printf("Queue head: %d\n", x);
return 0;
}
```
链式队列代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node, *QueuePtr;
typedef struct {
QueuePtr front, rear;
} LinkQueue;
void initQueue(LinkQueue *q) {
q->front = q->rear = (QueuePtr) malloc(sizeof(Node));
if (!q->front) {
printf("Memory allocation failed!\n");
exit(1);
}
q->front->next = NULL;
}
int isQueueEmpty(LinkQueue *q) {
return q->front == q->rear;
}
void enQueue(LinkQueue *q, int x) {
QueuePtr p = (QueuePtr) malloc(sizeof(Node));
if (!p) {
printf("Memory allocation failed!\n");
exit(1);
}
p->data = x;
p->next = NULL;
q->rear->next = p;
q->rear = p;
}
int deQueue(LinkQueue *q, int *x) {
if (isQueueEmpty(q)) {
printf("Queue is empty!\n");
return 0;
}
QueuePtr p = q->front->next;
*x = p->data;
q->front->next = p->next;
if (q->rear == p) {
q->rear = q->front;
}
free(p);
return 1;
}
int getHead(LinkQueue *q, int *x) {
if (isQueueEmpty(q)) {
printf("Queue is empty!\n");
return 0;
}
*x = q->front->next->data;
return 1;
}
void printQueue(LinkQueue *q) {
if (isQueueEmpty(q)) {
printf("Queue is empty!\n");
return;
}
printf("Queue: ");
QueuePtr p = q->front->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
LinkQueue q;
initQueue(&q);
enQueue(&q, 1);
enQueue(&q, 2);
enQueue(&q, 3);
printQueue(&q);
int x;
deQueue(&q, &x);
printf("Dequeue: %d\n", x);
printQueue(&q);
getHead(&q, &x);
printf("Queue head: %d\n", x);
return 0;
}
```
阅读全文