c语言单链表插入删除查找操作具体代码详解
时间: 2024-11-09 17:27:44 浏览: 14
C语言单链表实现19个功能完全详解.zip_C语言_C语言单链表_单链表
5星 · 资源好评率100%
在C语言中,单链表是一种常见的数据结构,它由一系列节点组成,每个节点包含数据域和指向下一个节点的指针。以下是单链表的插入、删除和查找操作的一些基本代码示例:
1. **插入操作** (在头部插入):
```c
typedef struct Node {
int data;
struct Node* next;
} Node;
void insertAtBeginning(Node** head, int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (!newNode) {
printf("Memory allocation failed.\n");
return;
}
newNode->data = value;
newNode->next = *head;
*head = newNode;
}
```
2. **插入操作** (在特定位置插入):
```c
void insertAfter(Node** head, int target, int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (!newNode) {
printf("Memory allocation failed.\n");
return;
}
newNode->data = value;
newNode->next = NULL;
Node* current = *head;
while (current != NULL && current->data != target) {
current = current->next;
}
if (current == NULL) {
printf("Target not found in the list.\n");
} else {
newNode->next = current->next;
current->next = newNode;
}
}
```
3. **删除操作** (根据值删除节点):
```c
void deleteNode(Node** head, int value) {
Node* temp = *head;
Node* prev = NULL;
if (temp != NULL && temp->data == value) {
*head = temp->next;
free(temp);
return;
}
while (temp != NULL && temp->data != value) {
prev = temp;
temp = temp->next;
}
if (temp == NULL) {
printf("Value not found in the list.\n");
} else {
prev->next = temp->next;
free(temp);
}
}
```
4. **查找操作** (按值查找节点):
```c
Node* searchNode(Node* head, int value) {
Node* current = head;
while (current != NULL) {
if (current->data == value)
return current;
current = current->next;
}
return NULL; // 如果未找到则返回NULL
}
```
阅读全文