帮我写一个双链表结构的记账函数
时间: 2024-02-13 16:04:28 浏览: 35
好的,以下是一个简单的双向链表结构的记账函数示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct _Record {
char name[20]; // 名字
double amount; // 金额
struct _Record *prev; // 前一个记录
struct _Record *next; // 后一个记录
} Record;
Record *head = NULL; // 链表头指针
// 添加一条记录
void addRecord(char *name, double amount) {
// 创建一个新节点
Record *newRecord = (Record*)malloc(sizeof(Record));
strcpy(newRecord->name, name);
newRecord->amount = amount;
newRecord->prev = NULL;
newRecord->next = NULL;
if (head == NULL) {
// 如果链表为空,将新节点作为链表头
head = newRecord;
} else {
// 否则将新节点插入到链表头之后
newRecord->next = head->next;
if (head->next != NULL) {
head->next->prev = newRecord;
}
head->next = newRecord;
newRecord->prev = head;
}
}
// 显示所有记录
void showRecords() {
Record *current = head;
while (current != NULL) {
printf("%s: %.2f\n", current->name, current->amount);
current = current->next;
}
}
// 删除所有记录
void clearRecords() {
Record *current = head;
while (current != NULL) {
Record *next = current->next;
free(current);
current = next;
}
head = NULL;
}
int main() {
addRecord("John", 10.0);
addRecord("Mike", 20.0);
addRecord("Lucy", 15.0);
showRecords();
clearRecords();
return 0;
}
```
以上代码实现了一个简单的双向链表结构,每个节点表示一条记录,包括名字和金额,可以添加、显示和清除所有记录。你可以根据自己的需求修改代码来实现更复杂的记账功能。