输入若干个不超过100的整数,建立单链表,然后通过一趟遍历在单链表中确定值最大的结点。输出该结点的值及其序号。
首先输入一个整数T,表示测试数据的组数,然后是T组测试数据。每组测试数据在一行上输入数据个数n及n个不超过100的整数。
对于每组测试,输出单链表中值最大的结点的值和该结点的序号。输出格式如下:
“max=dmax num=dnum”
其中,dmax表示最大的结点的值,dnum表示最大的结点的值所在结点的序号。若有多个相同的最大值,则以首次出现的为准。
1
30 85 97 43 70 69 29 77 22 64 25 55 39 95 69 99 61 97 69 59 12 88 55 75 66 13 75 36 85 67 69
max=99 num=15
?
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void insertAtEnd(struct Node** head, int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
} else {
struct Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
void findMax(struct Node* head) {
int max_value = head->data;
int max_index = 1; // 修改初始序号为1
int current_index = 1;
struct Node* current = head;
while (current != NULL) {
if (current->data > max_value) {
max_value = current->data;
max_index = current_index;
}
current = current->next;
current_index++;
}
printf("max=%d num=%d\n", max_value, max_index);
}
void freeLinkedList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
struct Node* temp = current;
current = current->next;
free(temp);
}
}
int main() {
int T;
scanf("%d", &T);
while (T--) {
int n;
scanf("%d", &n);
struct Node* head = NULL;
for (int i = 0; i < n; i++) {
int num;
scanf("%d", &num);
insertAtEnd(&head, num);
}
findMax(head);
freeLinkedList(head);
}
return 0;
}
?