单向链表增删改查的c代码
时间: 2024-09-18 10:05:20 浏览: 38
单向链表是一种线性的数据结构,每个节点包含数据和指向下一个节点的指针。以下是C语言中对单向链表进行增删改查的基本操作示例:
```c
// 定义链表节点结构体
typedef struct Node {
int data; // 节点的数据
struct Node* next; // 指向下一个节点的指针
} Node;
// 创建新节点函数
Node* createNode(int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = NULL;
return newNode;
}
// 插入节点到链表头部
void insertAtStart(Node** head, int value) {
Node* newNode = createNode(value);
newNode->next = *head;
*head = newNode;
}
// 插入节点到指定位置
void insertAfter(Node* current, int value) {
if (current == NULL) {
printf("Current node is null.\n");
return;
}
Node* newNode = createNode(value);
newNode->next = current->next;
current->next = newNode;
}
// 删除节点
void deleteNode(Node** head, int key) {
Node* temp = *head, *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) {
printf("Element not found in the list.\n");
return;
}
prev->next = temp->next;
free(temp);
}
// 查找节点
Node* findNode(Node* head, int key) {
Node* current = head;
while (current != NULL) {
if (current->data == key)
return current;
current = current->next;
}
return NULL;
}
// 打印链表
void printList(Node* head) {
Node* temp = head;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
```
阅读全文