c++代码实现链队列的基本操作
时间: 2023-10-30 20:20:50 浏览: 162
链队列的基本操作包括:初始化、入队、出队、获取队头元素、获取队列长度、清空队列、销毁队列。
下面是用 C 语言实现链队列的基本操作的代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
typedef struct Queue {
Node *front;
Node *rear;
int length;
} Queue;
// 初始化队列
void initQueue(Queue *queue) {
queue->front = queue->rear = NULL;
queue->length = 0;
}
// 入队
void enqueue(Queue *queue, int data) {
Node *node = (Node *) malloc(sizeof(Node));
node->data = data;
node->next = NULL;
if (queue->rear == NULL) {
queue->front = queue->rear = node;
} else {
queue->rear->next = node;
queue->rear = node;
}
queue->length++;
}
// 出队
void dequeue(Queue *queue) {
if (queue->front == NULL) {
printf("Queue is empty.\n");
return;
}
Node *node = queue->front;
queue->front = node->next;
if (queue->front == NULL) {
queue->rear = NULL;
}
free(node);
queue->length--;
}
// 获取队头元素
int front(Queue *queue) {
if (queue->front == NULL) {
printf("Queue is empty.\n");
return -1;
}
return queue->front->data;
}
// 获取队列长度
int getLength(Queue *queue) {
return queue->length;
}
// 清空队列
void clearQueue(Queue *queue) {
while (queue->front != NULL) {
dequeue(queue);
}
}
// 销毁队列
void destroyQueue(Queue *queue) {
clearQueue(queue);
free(queue);
}
int main() {
Queue *queue = (Queue *) malloc(sizeof(Queue));
initQueue(queue);
enqueue(queue, 1);
enqueue(queue, 2);
enqueue(queue, 3);
printf("Queue length: %d\n", getLength(queue));
printf("Queue front: %d\n", front(queue));
dequeue(queue);
printf("Queue length: %d\n", getLength(queue));
printf("Queue front: %d\n", front(queue));
clearQueue(queue);
printf("Queue length: %d\n", getLength(queue));
destroyQueue(queue);
return 0;
}
```
阅读全文