练习6--链表的操作(链表的建立、输出、找链上最大值、释放链表)
时间: 2024-05-24 09:12:36 浏览: 14
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct node {
int data;
struct node *next;
} Node;
// 建立链表
Node* createList(int n) {
Node *head = NULL, *tail = NULL;
int i, val;
for (i = 0; i < n; i++) {
printf("请输入第%d个节点的值:", i+1);
scanf("%d", &val);
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = val;
newNode->next = NULL;
if (tail == NULL) {
head = tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
return head;
}
// 输出链表
void printList(Node *head) {
Node *p = head;
printf("链表的值为:");
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
// 找链上最大值
int findMax(Node *head) {
int max = head->data;
Node *p = head->next;
while (p != NULL) {
if (p->data > max) {
max = p->data;
}
p = p->next;
}
return max;
}
// 释放链表
void freeList(Node *head) {
Node *p = head;
while (p != NULL) {
Node *tmp = p;
p = p->next;
free(tmp);
}
}
int main() {
int n;
printf("请输入链表的节点数:");
scanf("%d", &n);
Node *head = createList(n);
printList(head);
printf("链表中的最大值为:%d\n", findMax(head));
freeList(head);
return 0;
}
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)