用c语言编写一个程序实现链队列的各种基本运算,并在此基础上设计一个主程序,我成如下功能:(输出为中文) (1)初始化并建立链队列; (2)入队操作;(3)出队操作;(4) 遍历队列; (5)判断队空操作; (6),取队头和队尾操作 (7)求队长
时间: 2024-10-22 19:25:52 浏览: 24
在C语言中,我们可以使用结构体来表示链队列的数据节点,同时定义指向下一个节点的指针。这里是一个简单的链队列实现示例:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链队列节点结构
typedef struct Node {
int data;
struct Node* next;
} Node;
// 初始化链队列
Node* createQueue() {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = 0;
newNode->next = NULL;
return newNode;
}
// 入队操作
void enqueue(Node** head, int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = *head;
*head = newNode;
}
// 出队操作
int dequeue(Node** head) {
if (*head == NULL) {
printf("Error: Queue is empty.\n");
return -1; // 如果队列为空,返回错误值
}
int value = (*head)->data;
Node* temp = *head;
*head = (*head)->next;
free(temp);
return value;
}
// 遍历队列
void traverse(Node* head) {
Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
// 判断队空
int isQueueEmpty(Node* head) {
return head == NULL;
}
// 取队头
int getFront(Node* head) {
if (isQueueEmpty(head)) {
printf("Error: Queue is empty.\n");
return -1;
}
return head->data;
}
// 取队尾
int getRear(Node* head) {
if (isQueueEmpty(head)) {
printf("Error: Queue is empty.\n");
return -1;
}
Node* rear = head;
while (rear->next != NULL) {
rear = rear->next;
}
return rear->data;
}
// 主函数
int main() {
Node* queueHead = createQueue();
// 执行各项操作
printf("1. Initialize and build the queue\n");
printf("2. Enqueue elements\n");
printf("3. Dequeue elements\n");
printf("4. Traverse the queue\n");
printf("5. Check if queue is empty\n");
printf("6. Get front and rear of the queue\n");
printf("7. Find the first element in the queue (not implemented)\n");
// 示例操作
enqueue(&queueHead, 1);
enqueue(&queueHead, 2);
enqueue(&queueHead, 3);
printf("Queue after enqueue:\n");
traverse(queueHead);
int front = getFront(queueHead);
int rear = getRear(queueHead);
printf("Front element: %d\n", front);
printf("Rear element: %d\n", rear);
dequeue(&queueHead); // 出队第一个元素
printf("Queue after dequeue:\n");
traverse(queueHead);
return 0;
}
```
阅读全文