78 lines
1.6 KiB
C
78 lines
1.6 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
|
|
struct Node {
|
|
long int id;
|
|
char name[10];
|
|
double score;
|
|
struct Node *next;
|
|
};
|
|
|
|
struct Node* createNode() {
|
|
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
|
|
if (newNode == NULL) {
|
|
printf("記憶體分配失敗\n");
|
|
exit(1);
|
|
}
|
|
newNode->next = NULL;
|
|
return newNode;
|
|
}
|
|
|
|
void insertNode(struct Node** head) {
|
|
struct Node* newNode = createNode();
|
|
|
|
printf("請輸入學號: ");
|
|
scanf("%ld", &(newNode->id));
|
|
|
|
printf("請輸入姓名 (最多9個字符): ");
|
|
scanf("%9s", newNode->name);
|
|
|
|
printf("請輸入分數: ");
|
|
scanf("%lf", &(newNode->score));
|
|
|
|
if (*head == NULL) {
|
|
*head = newNode;
|
|
} else {
|
|
struct Node* current = *head;
|
|
while (current->next != NULL) {
|
|
current = current->next;
|
|
}
|
|
current->next = newNode;
|
|
}
|
|
|
|
printf("資料添加成功\n");
|
|
}
|
|
|
|
void printList(struct Node* head) {
|
|
struct Node* current = head;
|
|
while (current != NULL) {
|
|
printf("學號: %ld, 姓名: %s, 分數: %.2f\n", current->id, current->name, current->score);
|
|
current = current->next;
|
|
}
|
|
}
|
|
|
|
int main() {
|
|
struct Node* head = NULL;
|
|
char choice;
|
|
|
|
|
|
do {
|
|
insertNode(&head);
|
|
printf("是否繼續輸入? (y/n): ");
|
|
scanf(" %c", &choice);
|
|
} while (choice == 'y' || choice == 'Y');
|
|
|
|
printf("\n串列中的所有資料:\n");
|
|
printList(head);
|
|
|
|
// 釋放記憶體(實際應用中應該完整實現)
|
|
while (head != NULL) {
|
|
struct Node* temp = head;
|
|
head = head->next;
|
|
free(temp);
|
|
}
|
|
|
|
return 0;
|
|
}
|