建立两个单链表,一个用以存放冬奥会短道女子速滑运动员信息,另一个用来存放运动员成绩,利用指针实现单链表的基本操作。用类模板构造函数实现相关的操作:输出,插入,删除,查找等功能C语言
时间: 2024-11-29 09:16:28 浏览: 23
在C语言中,为了实现这个功能,我们可以创建两个结构体,分别表示运动员信息和成绩,然后通过链表数据结构来存储。这里我们使用`struct`关键字定义链表节点,并提供对应的`Node`结构体、链表头结点`List`以及相关的操作函数。
```c
#include <stdio.h>
#include <stdlib.h>
// 定义运动员信息节点
typedef struct AthleteInfo {
char name[50];
int age;
} AthleteInfo;
// 定义成绩节点
typedef struct Score {
AthleteInfo* info; // 指向运动员信息
float speed; // 速度分数
} Score;
// 链表头结点
typedef struct List {
AthleteInfo* athlete; // 存放运动员信息
Score* score; // 存放成绩
struct List* next; // 指向下一项
} Node, *ListNode;
// 构造函数
template <typename T>
ListNode createList(T firstElement) {
ListNode newNode = (ListNode)malloc(sizeof(Node));
newNode->athlete = &firstElement;
newNode->score = NULL;
newNode->next = NULL;
return newNode;
}
// 插入元素
template <typename T>
void insert(ListNode* list, T newElement) {
ListNode newNode = createList(newElement);
if (!list)
list = newNode;
else {
ListNode temp = list;
while (temp->next != NULL)
temp = temp->next;
temp->next = newNode;
}
}
// 输出链表内容
template <typename T>
void printList(ListNode* list) {
ListNode* temp = list;
while (temp != NULL) {
printf("Athlete: %s, Age: %d, Speed Score: %.2f\n",
temp->athlete->name, temp->athlete->age, temp->score->speed);
temp = temp->next;
}
}
// 删除元素(仅删除运动员信息,假设成绩不可见)
template <typename T>
void deleteElement(ListNode** list, const char* name) {
if (*list == NULL)
return;
if ((*list)->athlete->name == name) { // 如果找到要删除的节点
ListNode* temp = *list;
*list = (*list)->next;
free(temp); // 释放内存
return;
}
ListNode* current = *list;
while (current->next != NULL && strcmp(current->next->athlete->name, name) != 0)
current = current->next;
if (current->next != NULL) {
ListNode* toDelete = current->next;
current->next = toDelete->next;
free(toDelete);
}
}
// 查找元素
template <typename T>
ListNode* findElement(ListNode* list, const char* name) {
ListNode* temp = list;
while (temp != NULL) {
if (strcmp(temp->athlete->name, name) == 0)
return temp;
temp = temp->next;
}
return NULL; // 如果没找到,则返回NULL
}
int main() {
// 创建示例链表
AthleteInfo athlete1 = {"李琰", 32};
AthleteInfo athlete2 = {"王濛", 34};
AthleteInfo athlete3 = {"周洋", 28};
ListNode* athletesList = createList(athlete1);
insert< AthleteInfo >(athletesList, athlete2);
insert< AthleteInfo >(athletesList, athlete3);
printList< AthleteInfo >(athletesList);
deleteElement< AthleteInfo >(&athletesList, "王濛");
printList< AthleteInfo >(athletesList);
ListNode* found = findElement< AthleteInfo >(athletesList, "李琰");
if (found)
printf("Found athlete: %s\n", found->athlete->name);
else
printf("Athlete not found.\n");
return 0;
}
```
阅读全文