用c语言写一个链表实现一个电话号码本的功能,至少要包括,录入,删除,按使用频率排序,列出(显示全部),根据姓名查找号码,根据号码查找姓名等功能。
时间: 2024-12-19 17:13:47 浏览: 25
在 C 语言中,我们可以创建一个简单的链表结构来实现电话号码本的功能。这里是一个基础的示例,包含了一个`Node`结构用于存储电话记录,以及相应的函数来实现你的需求:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义 Node 结构
typedef struct PhoneBookNode {
char name[50];
char number[20];
int frequency; // 使用频率
struct PhoneBookNode* next;
} PhoneBookNode;
// 创建新的节点
PhoneBookNode* createNode(char* name, char* number) {
PhoneBookNode* newNode = (PhoneBookNode*)malloc(sizeof(PhoneBookNode));
if (newNode != NULL) {
strcpy(newNode->name, name);
strcpy(newNode->number, number);
newNode->frequency = 0;
newNode->next = NULL;
}
return newNode;
}
// 录入电话号码
void insert(PhoneBookNode** head, char* name, char* number) {
PhoneBookNode* newNode = createNode(name, number);
if (*head == NULL) {
*head = newNode;
} else {
PhoneBookNode* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
// 删除电话号码
void deleteEntry(PhoneBookNode** head, char* name) {
if (*head == NULL) return;
if ((*head)->name[0] == '\0') {
free(*head);
*head = (*head)->next;
return;
}
PhoneBookNode* temp = *head;
PhoneBookNode* prev = NULL;
while (temp != NULL && strcmp(temp->name, name) != 0) {
prev = temp;
temp = temp->next;
}
if (temp == NULL) return; // 没找到
if (prev == NULL) {
*head = temp->next;
} else {
prev->next = temp->next;
}
free(temp);
}
// 计算并更新使用频率
void updateFrequency(PhoneBookNode* node) {
for (node = node->next; node != NULL; node = node->next) {
node->frequency++;
}
}
// 根据使用频率排序链表
void sortByFrequency(PhoneBookNode** head) {
if (*head == NULL || (*head)->next == NULL) return;
PhoneBookNode* sortedList = *head;
PhoneBookNode* unsortedList = *head->next;
int count = 0;
while (unsortedList != NULL) {
PhoneBookNode* temp = unsortedList;
PhoneBookNode* prev = NULL;
while (count < temp->frequency) {
if (prev == NULL) {
sortedList = temp;
} else {
prev->next = temp;
}
temp = temp->next;
count++;
}
if (temp != NULL) {
prev->next = temp;
temp = unsortedList;
unsortedList = temp->next;
} else {
prev->next = NULL;
}
}
*head = sortedList;
}
// 显示全部联系人
void displayPhoneBook(PhoneBookNode* node) {
while (node != NULL) {
printf("Name: %s, Number: %s, Frequency: %d\n", node->name, node->number, node->frequency);
node = node->next;
}
}
// 查找联系人根据名字
char* findByName(PhoneBookNode* node, char* name) {
while (node != NULL) {
if (strcmp(node->name, name) == 0) {
return node->number;
}
node = node->next;
}
return "Not found";
}
// 查找联系人根据号码
char* findNumberByName(PhoneBookNode* node, char* number) {
while (node != NULL) {
if (strcmp(node->number, number) == 0) {
return node->name;
}
node = node->next;
}
return "Not found";
}
int main() {
// 初始化头节点
PhoneBookNode* phoneBookHead = NULL;
// 插入、删除、操作等...
return 0;
}
```
阅读全文