用C语言实现环形队列的各种基本操作。 (2)实现链队列的各种基本操作
时间: 2024-06-15 19:08:29 浏览: 125
c语言实现基本队列功能
环形队列是一种特殊的队列数据结构,它的特点是队尾指针可以循环回到队首。下面是用C语言实现环形队列的各种基本操作的示例代码:
1. 初始化环形队列
```c
#define MAX_SIZE 10
typedef struct {
int data[MAX_SIZE];
int front;
int rear;
} CircularQueue;
void initQueue(CircularQueue *queue) {
queue->front = 0;
queue->rear = 0;
}
```
2. 判断环形队列是否为空
```c
int isEmpty(CircularQueue *queue) {
return queue->front == queue->rear;
}
```
3. 判断环形队列是否已满
```c
int isFull(CircularQueue *queue) {
return (queue->rear + 1) % MAX_SIZE == queue->front;
}
```
4. 入队操作
```c
void enqueue(CircularQueue *queue, int item) {
if (isFull(queue)) {
printf("Queue is full.\n");
return;
}
queue->data[queue->rear] = item;
queue->rear = (queue->rear + 1) % MAX_SIZE;
}
```
5. 出队操作
```c
int dequeue(CircularQueue *queue) {
if (isEmpty(queue)) {
printf("Queue is empty.\n");
return -1;
}
int item = queue->data[queue->front];
queue->front = (queue->front + 1) % MAX_SIZE;
return item;
}
```
6. 获取队首元素
```c
int getFront(CircularQueue *queue) {
if (isEmpty(queue)) {
printf("Queue is empty.\n");
return -1;
}
return queue->data[queue->front];
}
```
7. 获取队列长度
```c
int getSize(CircularQueue *queue) {
return (queue->rear - queue->front + MAX_SIZE) % MAX_SIZE;
}
```
链队列是一种使用链表实现的队列数据结构,它的特点是队尾指针指向链表的最后一个节点。下面是用C语言实现链队列的各种基本操作的示例代码:
1. 定义链队列节点结构
```c
typedef struct Node {
int data;
struct Node *next;
} Node;
typedef struct {
Node *front;
Node *rear;
} LinkedQueue;
```
2. 初始化链队列
```c
void initQueue(LinkedQueue *queue) {
queue->front = NULL;
queue->rear = NULL;
}
```
3. 判断链队列是否为空
```c
int isEmpty(LinkedQueue *queue) {
return queue->front == NULL;
}
```
4. 入队操作
```c
void enqueue(LinkedQueue *queue, int item) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = item;
newNode->next = NULL;
if (isEmpty(queue)) {
queue->front = newNode;
queue->rear = newNode;
} else {
queue->rear->next = newNode;
queue->rear = newNode;
}
}
```
5. 出队操作
```c
int dequeue(LinkedQueue *queue) {
if (isEmpty(queue)) {
printf("Queue is empty.\n");
return -1;
}
Node *temp = queue->front;
int item = temp->data;
queue->front = queue->front->next;
free(temp);
if (queue->front == NULL) {
queue->rear = NULL;
}
return item;
}
```
6. 获取队首元素
```c
int getFront(LinkedQueue *queue) {
if (isEmpty(queue)) {
printf("Queue is empty.\n");
return -1;
}
return queue->front->data;
}
```
7. 获取队列长度
```c
int getSize(LinkedQueue *queue) {
int count = 0;
Node *current = queue->front;
while (current != NULL) {
count++;
current = current->next;
}
return count;
}
```
阅读全文