、请用户输入10首歌名,歌名存入一字符指针数组,然后分别按原序、字母序和字母逆序(从Z到A)显示这些歌名。
时间: 2024-10-21 10:14:13 浏览: 33
为了实现这个功能,你可以使用C语言编写程序。首先,你需要创建一个字符指针数组来存储歌曲名称,并提示用户输入10个歌名。然后,你可以定义三个函数分别用于按照原序、字母序和字母逆序排列数组。以下是简化的步骤:
```c
#include <stdio.h>
#include <string.h>
#define MAX_SONGS 10
// 定义歌曲结构体,包含歌名和指向下一个位置的指针
typedef struct {
char* song_name;
struct Song *next;
} Song;
// 功能:获取用户输入并存储歌名
void input_songs(Song** songs) {
for (int i = 0; i < MAX_SONGS; ++i) {
char song[MAX_SONG_NAME_LENGTH];
printf("请输入第 %d 首歌名:", i+1);
fgets(song, sizeof(song), stdin); // 去除换行符
song[strlen(song)-1] = '\0'; // 结束字符串
songs[i] = (Song*)malloc(sizeof(Song));
songs[i]->song_name = strdup(song);
songs[i]->next = NULL;
}
}
// 功能:按原顺序显示歌名
void display_original_order(Song* songs) {
for (Song* current = songs; current != NULL; current = current->next) {
printf("%s\n", current->song_name);
}
}
// 功能:按字母顺序排序并显示歌名
void sort_and_display_alphabetical_order(Song** songs) {
qsort(songs, MAX_SONGS, sizeof(Song*), compare_song_names);
for (Song* current = songs[0]; current != NULL; current = current->next) {
printf("%s\n", current->song_name);
}
}
// 比较函数,用于字典序排序
int compare_song_names(const void* a, const void* b) {
return strcmp(((Song*)a)->song_name, ((Song*)b)->song_name);
}
// 功能:按字母逆序排序并显示歌名
void sort_and_display_reverse_alphabetical_order(Song** songs) {
qsort(songs, MAX_SONGS, sizeof(Song*), reverse_compare_song_names);
for (Song* current = songs[MAX_SONGS - 1]; current != NULL; current = current->next) {
printf("%s\n", current->song_name);
}
}
// 反向比较函数,用于倒序排序
int reverse_compare_song_names(const void* a, const void* b) {
return strcmp(((Song*)b)->song_name, ((Song*)a)->song_name);
}
int main() {
Song* songs[MAX_SONGS];
input_songs(songs);
printf("\n原始顺序:\n");
display_original_order(songs);
printf("\n字母顺序:\n");
sort_and_display_alphabetical_order(songs);
printf("\n字母逆序:\n");
sort_and_display_reverse_alphabetical_order(songs);
// 清理内存
for (Song* current = songs[0]; current != NULL; current = current->next) {
free(current->song_name);
current->song_name = NULL;
}
return 0;
}
```
阅读全文