Data_Structure/作業/unit0/bowling_2_claude.c

115 lines
2.6 KiB
C
Raw Normal View History

2025-01-20 21:30:53 +08:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Player {
char name[8];
int score;
struct Player* next;
} Player;
Player* createPlayer(const char* name, int score) {
Player* newPlayer = (Player*)malloc(sizeof(Player));
if (newPlayer == NULL) {
fprintf(stderr, "<EFBFBD>O<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>t<EFBFBD><EFBFBD><EFBFBD><EFBFBD>\n");
exit(1);
}
strncpy(newPlayer->name, name, 7);
newPlayer->name[7] = '\0';
newPlayer->score = score;
newPlayer->next = NULL;
return newPlayer;
}
void addPlayer(Player** head, const char* name, int score) {
Player* newPlayer = createPlayer(name, score);
newPlayer->next = *head;
*head = newPlayer;
}
void sortPlayers(Player** head) {
int swapped;
Player* ptr1;
Player* lptr = NULL;
if (*head == NULL)
return;
do {
swapped = 0;
ptr1 = *head;
while (ptr1->next != lptr) {
if (ptr1->score < ptr1->next->score) {
int tempScore = ptr1->score;
char tempName[8];
strcpy(tempName, ptr1->name);
ptr1->score = ptr1->next->score;
strcpy(ptr1->name, ptr1->next->name);
ptr1->next->score = tempScore;
strcpy(ptr1->next->name, tempName);
swapped = 1;
}
ptr1 = ptr1->next;
}
lptr = ptr1;
} while (swapped);
}
void printResults(Player* head) {
printf("\n<EFBFBD><EFBFBD><EFBFBD>Z<EFBFBD>ƦW\n============\n");
int rank = 1;
while (head != NULL) {
if (rank == 1)
printf("%d. %s %d <20>a<EFBFBD>x\n", rank, head->name, head->score);
else if (rank == 2)
printf("%d. %s %d <20>ȭx\n", rank, head->name, head->score);
else if (rank == 3)
printf("%d. %s %d <20>u<EFBFBD>x\n", rank, head->name, head->score);
else
printf("%d. %s %d\n", rank, head->name, head->score);
head = head->next;
rank++;
}
}
void freeList(Player* head) {
Player* temp;
while (head != NULL) {
temp = head;
head = head->next;
free(temp);
}
}
int main() {
Player* head = NULL;
char input[32];
char name[8];
int score;
printf("<EFBFBD>гv<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>J<EFBFBD><EFBFBD><EFBFBD>ɪ̪<EFBFBD><EFBFBD><EFBFBD><EFBFBD>T...\n");
while (1) {
printf("<EFBFBD><EFBFBD><EFBFBD>J<EFBFBD><EFBFBD><EFBFBD>ɪ̦W<EFBFBD>r <20>o<EFBFBD><6F><EFBFBD>]<5D>Ϋ<EFBFBD>Enter<65><72><EFBFBD><EFBFBD><EFBFBD>^=> ");
if (fgets(input, sizeof(input), stdin) == NULL || strcmp(input, "\n") == 0) {
break;
}
if (sscanf(input, "%7s %d", name, &score) == 2) {
addPlayer(&head, name, score);
} else {
printf("<EFBFBD><EFBFBD><EFBFBD>J<EFBFBD><EFBFBD><EFBFBD><EFBFBD>~<7E>A<EFBFBD>Э<EFBFBD><D0AD>s<EFBFBD><73><EFBFBD>J<EFBFBD>C\n");
}
}
sortPlayers(&head);
printResults(head);
freeList(head);
return 0;
}