利用链表建立一个数组,用户输入N,再输入N个数,计算其中的最小值位置(从1开始编号)。
1、 第1位同学负责设计结构体和主函数的编写;
2、 第2位同学负责建立链表(包括读取数据);
函数原型:struct node * Create();
3、 第3位同学负责输出这N个数;
函数原型:void Print(struct node * head);
4、 第4位同学负责找出最小值的位置;
函数原型:int Min(struct node * head)
基于new bing的编写参考:
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
struct node * Create(int n) {
struct node *head = NULL, *p = NULL, *q = NULL;
for (int i = 0; i < n; i++) {
p = (struct node *)malloc(sizeof(struct node));
printf("请输入第 %d 个数字:", i + 1);
scanf("%d", &(p->data));
p->next = NULL;
if (head == NULL) {
head = p;
} else {
q->next = p;
}
q = p;
}
return head;
}
void Print(struct node *head) {
if (head == NULL) {
printf("链表为空!\n");
} else {
printf("输入的数字为:");
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
}
int Min(struct node *head) {
int pos = 1, min_pos = 1;
int min = head->data;
while (head != NULL) {
if (head->data < min) {
min = head->data;
min_pos = pos;
}
head = head->next;
pos++;
}
return min_pos;
}
int main() {
int n;
printf("请输入 N:");
scanf("%d", &n);
struct node *head = NULL;
head = Create(n);
Print(head);
int min_pos = Min(head);
printf("最小值的位置是:%d\n", min_pos);
return 0;
}
#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, min_pos;
struct node *head;
printf("请输入N:");
scanf("%d", &N);
head = Create(N);
printf("打印输入的N个数:\n");
Print(head);
min_pos = Min(head);
printf("最小值位置是:%d\n", min_pos);
return 0;
}
struct node *Create(int N) {
int i;
struct node *head, *p, *tail;
head = NULL;
for (i = 1; i <= N; i++) {
p = (struct node *) malloc(sizeof(struct node));
printf("请输入第%d个数:", i);
scanf("%d", &p->data);
p->next = NULL;
if (head == NULL) {
head = p;
tail = p;
} else {
tail->next = p;
tail = p;
}
}
return head;
}
void Print(struct node *head) {
struct node *p;
p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int Min(struct node *head) {
struct node *p;
int min_value, min_pos, i;
p = head;
min_value = p->data;
min_pos = 1;
i = 1;
while (p != NULL) {
if (p->data < min_value) {
min_value = p->data;
min_pos = i;
}
i++;
p = p->next;
}
return min_pos;
}