c语言先建立数据元素类型为int的链队列,设计算法求最大值元素及个数
时间: 2024-05-16 22:13:20 浏览: 79
C语言中链队列的实现
以下是建立数据元素类型为int的链队列的代码实现,包括入队、出队和遍历队列的函数:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
typedef struct Queue {
Node* front;
Node* rear;
} Queue;
void initQueue(Queue* queue) {
queue->front = queue->rear = NULL;
}
void enqueue(Queue* queue, int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (queue->front == NULL) {
queue->front = newNode;
} else {
queue->rear->next = newNode;
}
queue->rear = newNode;
}
int dequeue(Queue* queue) {
if (queue->front == NULL) {
printf("Queue is empty.\n");
return -1;
}
int data = queue->front->data;
Node* temp = queue->front;
queue->front = queue->front->next;
free(temp);
return data;
}
void traverseQueue(Queue* queue) {
Node* p = queue->front;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
```
接下来是求最大值元素及个数的算法实现,具体过程如下:
1. 定义一个变量max,初始值为队首元素的值,定义一个变量count,初始值为1。
2. 从队列的第二个元素开始遍历队列,如果当前元素的值大于max,就更新max的值为当前元素的值,并将count重置为1。
3. 如果当前元素的值等于max,就将count加1。
4. 遍历完队列后,输出max的值和count的值。
以下是完整代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
typedef struct Queue {
Node* front;
Node* rear;
} Queue;
void initQueue(Queue* queue) {
queue->front = queue->rear = NULL;
}
void enqueue(Queue* queue, int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (queue->front == NULL) {
queue->front = newNode;
} else {
queue->rear->next = newNode;
}
queue->rear = newNode;
}
int dequeue(Queue* queue) {
if (queue->front == NULL) {
printf("Queue is empty.\n");
return -1;
}
int data = queue->front->data;
Node* temp = queue->front;
queue->front = queue->front->next;
free(temp);
return data;
}
void traverseQueue(Queue* queue) {
Node* p = queue->front;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
void getMaxElementAndCount(Queue* queue, int* max, int* count) {
*max = queue->front->data;
*count = 1;
Node* p = queue->front->next;
while (p != NULL) {
if (p->data > *max) {
*max = p->data;
*count = 1;
} else if (p->data == *max) {
(*count)++;
}
p = p->next;
}
}
int main() {
Queue queue;
initQueue(&queue);
enqueue(&queue, 5);
enqueue(&queue, 7);
enqueue(&queue, 3);
enqueue(&queue, 9);
enqueue(&queue, 7);
traverseQueue(&queue);
int max, count;
getMaxElementAndCount(&queue, &max, &count);
printf("Max element is %d, count is %d.\n", max, count);
return 0;
}
```
输出结果为:
```
5 7 3 9 7
Max element is 9, count is 1.
```
阅读全文