生成实现链表的增删查找c语言代码
时间: 2024-11-20 16:45:05 浏览: 5
在C语言中,我们可以使用结构体和指针来创建简单的链表数据结构,并实现增、删、查的操作。下面是一个基本的单向链表的简单实现:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct Node {
int data;
struct Node* next;
} Node;
// 创建新节点
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (newNode == NULL) {
printf("Memory allocation failed.\n");
return NULL;
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// 添加元素到链表尾部
void appendNode(Node** head, int data) {
if (*head == NULL) {
*head = createNode(data);
} else {
Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = createNode(data);
}
}
// 查找元素
Node* searchNode(Node* head, int key) {
Node* current = head;
while (current != NULL) {
if (current->data == key) {
return current;
}
current = current->next;
}
return NULL; // 如果未找到,返回NULL
}
// 删除节点
void deleteNode(Node** head, int key) {
if (*head == NULL) {
return;
}
if ((*head)->data == key) {
Node* temp = *head;
*head = (*head)->next;
free(temp);
return;
}
Node* current = *head;
while (current->next != NULL && current->next->data != key) {
current = current->next;
}
if (current->next != NULL) {
Node* temp = current->next;
current->next = temp->next;
free(temp);
}
}
int main() {
Node* head = NULL;
appendNode(&head, 10);
appendNode(&head, 20);
appendNode(&head, 30);
Node* found = searchNode(head, 20);
if (found) {
printf("Found element: %d\n", found->data);
} else {
printf("Element not found.\n");
}
deleteNode(&head, 20);
return 0;
}
```
阅读全文