python编程:把一堆苹果分给n个小朋友,要使每个人都能拿到苹果,而且每个人拿到的苹果数都不同的话,这堆苹果至少应该有多少个
时间: 2023-05-15 22:04:50 浏览: 117
可以使用以下代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义学生结构体
typedef struct student {
int id;
char name[20];
int score;
struct student *next;
} Student;
// 从文件中读取学生信息并创建链表
Student *createListFromFile(char *filename) {
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
printf("Failed to open file %s\n", filename);
return NULL;
}
Student *head = NULL;
Student *tail = NULL;
while (!feof(fp)) {
Student *s = (Student *)malloc(sizeof(Student));
fscanf(fp, "%d %s %d", &s->id, s->name, &s->score);
s->next = NULL;
if (head == NULL) {
head = s;
tail = s;
} else {
tail->next = s;
tail = s;
}
}
fclose(fp);
return head;
}
// 删除指定学号的学生节点
void deleteStudent(Student **head, int id) {
Student *prev = NULL;
Student *curr = *head;
while (curr != NULL) {
if (curr->id == id) {
if (prev == NULL) {
*head = curr->next;
} else {
prev->next = curr->next;
}
free(curr);
printf("Deleted student with ID %d\n", id);
return;
}
prev = curr;
curr = curr->next;
}
printf("Student with ID %d not found\n", id);
}
// 打印链表中的所有学生信息
void printList(Student *head) {
printf("ID\tName\tScore\n");
printf("--------------------\n");
Student *curr = head;
while (curr != NULL) {
printf("%d\t%s\t%d\n", curr->id, curr->name, curr->score);
curr = curr->next;
}
}
int main() {
// 从文件中创建链表
Student *head = createListFromFile("students.txt");
if (head == NULL) {
return 1;
}
// 打印链表中的所有学生信息
printList(head);
// 删除指定学号的学生节点
int id;
printf("Enter student ID to delete: ");
scanf("%d", &id);
deleteStudent(&head, id);
// 打印删除后的链表中的所有学生信息
printList(head);
return 0;
}
```
其中,`createListFromFile` 函数从文件中读取学生信息并创建链表,`deleteStudent` 函数删除指定学号的学生节点,`printList` 函数打印链表中的所有学生信息。在 `main` 函数中,先调用 `createListFromFile` 函数创建链表,然后调用 `printList` 函数打印链表中的所有学生信息,接着调用 `deleteStudent` 函数删除指定学号的学生节点,最后再调用 `printList` 函数打印删除后的链表中的所有学生信息。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)