c语言链表订餐管理系统
时间: 2023-12-30 14:24:06 浏览: 30
以下是一个简单的C语言链表订餐管理系统的示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义菜品结构体
typedef struct Dish {
int id;
char name[100];
float price;
struct Dish* next;
} Dish;
// 全局变量,指向链表头节点
Dish* head = NULL;
// 创建新菜品节点
Dish* createDish(int id, char name[], float price) {
Dish* newDish = (Dish*)malloc(sizeof(Dish));
newDish->id = id;
strcpy(newDish->name, name);
newDish->price = price;
newDish->next = NULL;
return newDish;
}
// 添加菜品到链表
void addDish(int id, char name[], float price) {
Dish* newDish = createDish(id, name, price);
if (head == NULL) {
head = newDish;
} else {
Dish* current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newDish;
}
}
// 打印菜单
void printMenu() {
Dish* current = head;
printf("菜单:\n");
while (current != NULL) {
printf("ID:%d,名称:%s,价格:%.2f\n", current->id, current->name, current->price);
current = current->next;
}
}
// 查找菜品
Dish* findDish(int id) {
Dish* current = head;
while (current != NULL) {
if (current->id == id) {
return current;
}
current = current->next;
}
return NULL;
}
// 删除菜品
void deleteDish(int id) {
Dish* current = head;
Dish* previous = NULL;
while (current != NULL) {
if (current->id == id) {
if (previous == NULL) {
head = current->next;
} else {
previous->next = current->next;
}
free(current);
return;
}
previous = current;
current = current->next;
}
}
int main() {
// 添加菜品到链表
addDish(1, "鱼香肉丝", 18.0);
addDish(2, "宫保鸡丁", 20.0);
addDish(3, "红烧肉", 25.0);
// 打印菜单
printMenu();
// 查找菜品
int dishId = 2;
Dish* foundDish = findDish(dishId);
if (foundDish != NULL) {
printf("找到了ID为%d的菜品:%s,价格:%.2f\n", dishId, foundDish->name, foundDish->price);
} else {
printf("未找到ID为%d的菜品\n", dishId);
}
// 删除菜品
int deleteId = 3;
deleteDish(deleteId);
printf("删除ID为%d的菜品后的菜单:\n", deleteId);
printMenu();
return 0;
}
```