(数据结构)利用 C语言实现顺序队列及链队列
时间: 2023-05-24 11:05:14 浏览: 110
1. 顺序队列实现
```c
#include <stdio.h>
#define MAX_SIZE 10
typedef struct {
int data[MAX_SIZE];
int front; // 队头指针,指向第一个元素
int rear; // 队尾指针,指向最后一个元素的下一个位置
} SeqQueue;
void initSeqQueue(SeqQueue *queue) {
queue->front = 0;
queue->rear = 0;
}
int isSeqQueueEmpty(SeqQueue *queue) {
return queue->front == queue->rear;
}
int isSeqQueueFull(SeqQueue *queue) {
return (queue->rear + 1) % MAX_SIZE == queue->front;
}
void enSeqQueue(SeqQueue *queue, int data) {
if (isSeqQueueFull(queue)) {
printf("Queue is full.\n");
return;
}
queue->data[queue->rear] = data;
queue->rear = (queue->rear + 1) % MAX_SIZE;
}
int deSeqQueue(SeqQueue *queue) {
if (isSeqQueueEmpty(queue)) {
printf("Queue is empty.\n");
return -1;
}
int data = queue->data[queue->front];
queue->front = (queue->front + 1) % MAX_SIZE;
return data;
}
int main() {
SeqQueue queue;
initSeqQueue(&queue);
enSeqQueue(&queue, 1);
enSeqQueue(&queue, 2);
enSeqQueue(&queue, 3);
printf("%d ", deSeqQueue(&queue));
printf("%d ", deSeqQueue(&queue));
printf("%d\n", deSeqQueue(&queue));
enSeqQueue(&queue, 4);
enSeqQueue(&queue, 5);
enSeqQueue(&queue, 6);
enSeqQueue(&queue, 7);
enSeqQueue(&queue, 8);
enSeqQueue(&queue, 9);
enSeqQueue(&queue, 10);
printf("%d ", deSeqQueue(&queue));
printf("%d\n", deSeqQueue(&queue));
enSeqQueue(&queue, 11);
return 0;
}
```
2. 链队列实现
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct LinkNode {
int data;
struct LinkNode *next;
} LinkNode;
typedef struct {
LinkNode *front; // 队头指针
LinkNode *rear; // 队尾指针
} LinkQueue;
void initLinkQueue(LinkQueue *queue) {
queue->front = queue->rear = (LinkNode*)malloc(sizeof(LinkNode));
queue->front->next = NULL;
}
int isLinkQueueEmpty(LinkQueue *queue) {
return queue->front == queue->rear;
}
void enLinkQueue(LinkQueue *queue, int data) {
LinkNode *node = (LinkNode*)malloc(sizeof(LinkNode));
node->data = data;
node->next = NULL;
queue->rear->next = node;
queue->rear = node;
}
int deLinkQueue(LinkQueue *queue) {
if (isLinkQueueEmpty(queue)) {
printf("Queue is empty.\n");
return -1;
}
int data = queue->front->next->data;
LinkNode *temp = queue->front->next;
queue->front->next = temp->next;
if (queue->rear == temp) {
queue->rear = queue->front;
}
free(temp);
return data;
}
int main() {
LinkQueue queue;
initLinkQueue(&queue);
enLinkQueue(&queue, 1);
enLinkQueue(&queue, 2);
enLinkQueue(&queue, 3);
printf("%d ", deLinkQueue(&queue));
printf("%d ", deLinkQueue(&queue));
printf("%d\n", deLinkQueue(&queue));
enLinkQueue(&queue, 4);
enLinkQueue(&queue, 5);
enLinkQueue(&queue, 6);
enLinkQueue(&queue, 7);
enLinkQueue(&queue, 8);
enLinkQueue(&queue, 9);
enLinkQueue(&queue, 10);
printf("%d ", deLinkQueue(&queue));
printf("%d\n", deLinkQueue(&queue));
enLinkQueue(&queue, 11);
return 0;
}
```
阅读全文