写一个智能车双向链表的C语言程序
时间: 2024-09-24 13:02:51 浏览: 38
在C语言中,我们可以创建一个简单的双向链表结构来表示智能车的数据,并提供插入、删除等操作。首先,我们定义节点结构体`SmartCarNode`,然后实现链表头结点`SmartCarList`的一些基本功能。以下是一个简化的示例:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义节点结构
typedef struct SmartCarNode {
char carID[50];
struct SmartCarNode* prev;
struct SmartCarNode* next;
} SmartCarNode;
// 链表头结点
typedef SmartCarNode* SmartCarList;
// 插入节点到链表尾部
void insert(SmartCarList* list, const char* carID) {
SmartCarNode* newNode = (SmartCarNode*)malloc(sizeof(SmartCarNode));
strcpy(newNode->carID, carID);
newNode->prev = NULL;
newNode->next = NULL;
if (*list == NULL) { // 如果链表为空
*list = newNode;
} else {
SmartCarNode* temp = *list;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
newNode->prev = temp;
}
}
// 删除节点(根据车ID)
void deleteByID(SmartCarList* list, const char* carID) {
SmartCarNode* current = *list;
SmartCarNode* previous = NULL;
while (current != NULL && strcmp(current->carID, carID) != 0) {
previous = current;
current = current->next;
}
if (current != NULL) {
if (previous == NULL) { // 如果要删除的是头节点
*list = current->next;
} else {
previous->next = current->next;
}
free(current);
}
}
// 打印链表中的所有车ID
void printList(SmartCarList list) {
SmartCarNode* temp = list;
while (temp != NULL) {
printf("%s -> ", temp->carID);
temp = temp->next;
}
printf("NULL\n");
}
int main() {
SmartCarList cars = NULL;
// 插入节点
insert(&cars, "Car1");
insert(&cars, "Car2");
insert(&cars, "Car3");
// 打印链表
printList(cars);
// 删除某个节点
deleteByID(&cars, "Car2");
// 再次打印链表
printList(cars);
return 0;
}
```
阅读全文