一个用AI生成的链表代码。
尝试使用AI生成一段链表代码,放入编译器后直接编译就可以通过,稍微修改就可以用在实际的项目当中,比自己敲代码来的方便多了,AI好好使用是能提升很大的工作效率的。但是首先需要你知道你想要的是什么,如果不知道你想要的,你也无法让AI帮你做事情。
#include <stdio.h>
#include <stdlib.h>
// 定义节点结构
struct Node {
int data;
struct Node* next;
};
// 创建新节点
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// 插入节点到链表头部
void insertAtHead(struct Node** head, int data) {
struct Node* newNode = createNode(data);
newNode->next = *head;
*head = newNode;
}
// 删除链表中的节点
void deleteNode(struct Node** head, int key) {
struct Node* temp = *head;
struct Node* prev = NULL;
// 如果头节点就是要删除的节点
if (temp != NULL && temp->data == key) {
*head = temp->next;
free(temp);
return;
}
// 查找要删除的节点
while (temp != NULL && temp->data != key) {
prev = temp;
temp = temp->next;
}
// 如果没有找到要删除的节点
if (temp == NULL) return;
// 解除节点的链接
prev->next = temp->next;
free(temp);
}
// 打印链表
void printList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("0x%x -> ", current->data);
current = current->next;
}
printf("NULL\n");
}
// 遍历链表并对每个节点的数据执行操作
void traverseList(struct Node* head, void (*func)(int)) {
struct Node* current = head;
while (current != NULL) {
func(current->data);
current = current->next;
}
}
// 打印节点数据的函数
void printData(int data) {
printf("%d ", data);
}
int main() {
struct Node* head = NULL;
int a,b,c,d;
insertAtHead(&head, (int)&a);
insertAtHead(&head, (int)&b);
insertAtHead(&head, (int)&c);
insertAtHead(&head, (int)&d);
printf("Linked List: ");
printList(head);
printf("Deleting node with data 3\n");
deleteNode(&head, (int)&b);
printf("Linked List after deletion: ");
printList(head);
printf("Traversing the list: ");
traverseList(head, printData);
printf("\n");
return 0;
}
```