用C语言来写单向链表的插入与删除操作
时间: 2024-09-24 10:02:24 浏览: 38
在C语言中,我们可以使用结构体(struct)和指针来创建和操作单向链表。以下是基本的插入和删除操作:
### 单向链表节点定义
```c
typedef struct Node {
int data; // 数据域
struct Node* next; // 指向下一个节点的指针
} Node;
```
#### 插入操作
- **在头部插入**:
```c
void insertAtBeginning(Node** head, int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = *head;
*head = newNode;
}
```
- **在尾部插入**:
```c
void insertAtEnd(Node** head, int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
if (*head == NULL) {
*head = newNode;
return;
}
Node* current = *head;
while (current->next != NULL)
current = current->next;
current->next = newNode;
}
```
- **在指定位置插入**:
```c
void insertAfter(Node** head, int key, int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
Node* current = *head;
while (current && current->data != key) {
current = current->next;
}
if (current) {
newNode->next = current->next;
current->next = newNode;
} else {
printf("Element not found\n");
}
}
```
#### 删除操作
- **删除头部元素**:
```c
void deleteFirst(Node** head) {
if (*head == NULL)
return;
Node* temp = *head;
*head = (*head)->next;
free(temp);
}
```
- **删除特定值的元素**:
```c
void deleteNode(Node** head, int value) {
if (*head == NULL)
return;
if ((*head)->data == value) {
Node* temp = *head;
*head = (*head)->next;
free(temp);
return;
}
Node* current = *head;
while (current->next != NULL && current->next->data != value) {
current = current->next;
}
if (current->next != NULL) {
Node* toBeDeleted = current->next;
current->next = current->next->next;
free(toBeDeleted);
}
}
```
阅读全文