输入若干个不超过100的整数,建立单链表,然后通过一趟遍历在单链表中确定值最大的结点。输出该结点的值及其序号。 具体代码
时间: 2024-06-06 22:08:43 浏览: 5
#include <stdio.h>
#include <stdlib.h>
typedef struct Node{
int data; // 结点数据
struct Node *next; // 下一节点指针
}Node, *LinkedList;
LinkedList createLinkedList(); // 创建链表
void traverseLinkedList(LinkedList); // 遍历链表
void findMaxNode(LinkedList); // 查找最大值结点
int main(){
LinkedList list = createLinkedList(); // 创建链表
traverseLinkedList(list); // 遍历链表
findMaxNode(list); // 查找最大值结点
return 0;
}
LinkedList createLinkedList(){
LinkedList head, p, q;
head = (LinkedList)malloc(sizeof(Node)); // 创建头结点
head->next = NULL; // 头结点指针域为空
q = head; // 指针q指向头结点
int data;
printf("请输入若干个整数,以-1结束:\n");
scanf("%d", &data);
while(data != -1){
p = (LinkedList)malloc(sizeof(Node));
p->data = data;
q->next = p;
q = p;
scanf("%d", &data);
}
q->next = NULL; // 尾结点指针域为空
return head;
}
void traverseLinkedList(LinkedList head){
LinkedList p = head->next; // 指针p指向头结点的下一节点
int i = 1;
while(p != NULL){
printf("结点%d的值为%d\n", i, p->data);
p = p->next;
i++;
}
}
void findMaxNode(LinkedList head){
LinkedList p = head->next; // 指针p指向头结点的下一节点
int maxValue = p->data; // 初始化最大值为第一个结点的值
int maxIndex = 1; // 初始化最大值结点的序号为1
int i = 1;
while(p != NULL){
if(p->data > maxValue){
maxValue = p->data;
maxIndex = i;
}
p = p->next;
i++;
}
printf("最大值为%d,序号为%d\n", maxValue, maxIndex);
}
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)