编写程序输入n个整数链式存放并输出最大值
时间: 2023-06-10 15:08:04 浏览: 33
以下是一个用 C 语言实现的示例代码:
```
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
int main() {
int n, max = 0;
struct node *head, *tail, *p;
head = tail = (struct node*)malloc(sizeof(struct node));
scanf("%d", &n);
for (int i = 0; i < n; i++) {
p = (struct node*)malloc(sizeof(struct node));
scanf("%d", &p->data);
tail->next = p;
tail = p;
}
tail->next = NULL;
p = head->next;
while (p != NULL) {
if (p->data > max) {
max = p->data;
}
p = p->next;
}
printf("最大值: %d\n", max);
return 0;
}
```
这个代码实现了读入 n 个整数,并使用链式存储,最后输出最大值的功能。
相关问题
编写程序,输入n个整数链式存放并输出最大值。
以下是一个Python的实现:
```python
class Node:
def __init__(self, val):
self.val = val
self.next = None
def find_max(head):
if not head:
return None
max_val = head.val
node = head
while node:
if node.val > max_val:
max_val = node.val
node = node.next
return max_val
# 示例
head = Node(1)
head.next = Node(3)
head.next.next = Node(5)
head.next.next.next = Node(2)
print(find_max(head)) # 输出5
```
首先定义了一个链表节点类 `Node`,包含一个整数值 `val` 和一个指向下一个节点的指针 `next`。然后定义了函数 `find_max`,接受链表的头节点作为参数,遍历整个链表,找到最大值并返回。在遍历过程中,用一个变量 `max_val` 记录当前找到的最大值,初始值为头节点的值。每次遍历到一个节点时,如果它的值比 `max_val` 大,就更新 `max_val`。最后返回 `max_val` 即可。
用C语言编写程序,输入n个整数链式存放并输出最大值。
以下是用C语言编写程序,输入n个整数链式存放并输出最大值的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct node {
int data;
struct node *next;
} Node;
int main() {
int n, i, max;
Node *head, *p, *q;
// 输入链表长度n
printf("请输入链表长度n:");
scanf("%d", &n);
// 初始化链表头节点
head = (Node *)malloc(sizeof(Node));
head->next = NULL;
p = head;
// 输入n个整数并添加到链表中
printf("请输入%d个整数:", n);
for (i = 0; i < n; i++) {
q = (Node *)malloc(sizeof(Node));
scanf("%d", &q->data);
q->next = NULL;
p->next = q;
p = q;
}
// 遍历链表查找最大值
p = head->next;
max = p->data;
while (p != NULL) {
if (p->data > max) {
max = p->data;
}
p = p->next;
}
// 输出最大值
printf("最大值为:%d\n", max);
// 释放链表节点内存
p = head;
while (p != NULL) {
q = p->next;
free(p);
p = q;
}
return 0;
}
```
在上述代码中,首先定义了链表节点结构体 `Node`,包含整数数据 `data` 和指向下一个节点的指针 `next`。然后在 `main` 函数中,输入链表长度n,并初始化链表头节点 `head`。接着输入n个整数,并依次添加到链表中。然后遍历链表查找最大值,最后输出最大值并释放链表节点内存。