利用链表建立一个数组,用户输入N,再输入N个数,计算其中的最小值位置(从1开始编号)。 1、 设计结构体和主函数的编写; 2、 建立链表(包括读取数据); 函数原型:struct node * Create(); 3、 输出这N个数; 函数原型:void Print(struct node * head); 4、 找出最小值的位置; 函数原型:int Min(struct node * head);
时间: 2024-03-10 18:50:16 浏览: 22
好的,我知道了,以下是代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *Create(int n);
void Print(struct node *head);
int Min(struct node *head);
int main() {
int n;
printf("请输入N的值:");
scanf("%d", &n);
struct node *head = Create(n);
printf("输入的%d个数为:\n", n);
Print(head);
int minPos = Min(head);
printf("最小值的位置是:%d\n", minPos);
return 0;
}
struct node *Create(int n) {
struct node *head = NULL;
struct node *p = NULL;
for (int i = 0; i < n; i++) {
int num;
printf("请输入第%d个数:", i + 1);
scanf("%d", &num);
struct node *newNode = (struct node *)malloc(sizeof(struct node));
newNode->data = num;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
p = head;
} else {
p->next = newNode;
p = newNode;
}
}
return head;
}
void Print(struct node *head) {
struct node *p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int Min(struct node *head) {
int minPos = 1;
int minVal = head->data;
struct node *p = head->next;
int pos = 2;
while (p != NULL) {
if (p->data < minVal) {
minPos = pos;
minVal = p->data;
}
p = p->next;
pos++;
}
return minPos;
}
```
使用方法:
1. 将以上代码保存为 `main.c` 文件;
2. 编译运行:
```
$ gcc main.c -o main
$ ./main
```
3. 按照提示输入 `N` 和 `N` 个数;
4. 程序会输出这 `N` 个数和最小值的位置。
希望能够帮到你!