1 #include <stdio.h>
2 #include <stdlib.h>
3
4 #define MAX_SIZE 100
5
6 // 队列结构
7 typedef struct {
8 int data[MAX_SIZE];
9 int front;
10 int rear;
11 } Queue;
12
13 // 初始化队列
14 void initQueue(Queue* queue) {
15 queue->front = -1;
16 queue->rear = -1;
17 }
18
19 // 判断队列是否为空
20 int isEmpty(Queue* queue) {
21 return queue->front == -1;
22 }
23
24 // 判断队列是否已满
25 int isFull(Queue* queue) {
26 return (queue->rear + 1) % MAX_SIZE == queue->front;
27 }
28
29 // 入队
30 void enqueue(Queue* queue, int value) {
31 if (isFull(queue)) {
32 printf("队列已满,无法入队\n");
33 return;
34 }
35
36 if (isEmpty(queue)) {
37 queue->front = 0;
38 queue->rear = 0;
39 } else {
40 queue->rear = (queue->rear + 1) % MAX_SIZE;
41 }
42
43 queue->data[queue->rear] = value;
44 printf("入队成功:%d\n", value);
45 }
46
47 // 出队
48 int dequeue(Queue* queue) {
49 if (isEmpty(queue)) {
50 printf("队列为空,无法出队\n");
51 return -1;
52 }
53
54 int value = queue->data[queue->front];
55
56 if (queue->front == queue->rear) {
57 queue->front = -1;
58 queue->rear = -1;
59 } else {
60 queue->front = (queue->front + 1) % MAX_SIZE;
61 }
62
63 printf("出队成功:%d\n", value);
64 return value;
65 }
66
67 // 更新队列中指定位置的元素
68 void update(Queue* queue, int index, int value) {
69 if (isEmpty(queue)) {
70 printf("队列为空,无法更新元素\n");
71 return;
72 }
73
74 if (index < 0 || index > (queue->rear - queue->front)) {
75 printf("索引超出范围,无法更新元素\n");
76 return;
77 }
78
79 int pos = (queue->front + index) % MAX_SIZE;
80 queue->data[pos] = value;
81 printf("更新成功,位置 %d 的元素更新为:%d\n", index, value);
82 }
83
84 // 查找指定元素在队列中的位置
85 int search(Queue* queue, int value) {
86 if (isEmpty(queue)) {
87 printf("队列为空,无法查找元素\n");
88 return -1;
89 }
90
91 int index = 0;
92 int i = queue->front;
93
94 while (i != queue->rear) {
95 if (queue->data[i] == value) {
96 printf("元素 %d 在队列中的位置为:%d\n", value, index);
97 return index;
98 }
99
100 i = (i + 1) % MAX_SIZE;
101 index++;
102 }
103
104 printf("队列中不存在元素 %d\n", value);
105 return -1;
106 }
107
108 // 主函数
109 int main() {
110 Queue queue;
111 initQueue(&queue);
112
113 enqueue(&queue, 10);
114 enqueue(&queue, 20);
115 enqueue(&queue, 30);
116
117 search(&queue, 20);
118
119 update(&queue, 1, 40);
120
121 dequeue(&queue);
122 dequeue(&queue);
123
124 return 0;
125 }