单链表的插入和删除c++
时间: 2023-12-18 12:23:21 浏览: 107
单链表的插入与删除
单链表的插入和删除操作是链表的基本操作之一。在C语言中,可以通过以下代码实现单链表的插入和删除:
插入操作的代码如下:
```c
void InsertNode(struct Node **head, int data) {
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
} else {
struct Node *current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
```
删除操作的代码如下:
```c
void DeleteNode(struct Node **head, int data) {
if (*head == NULL) {
return;
}
struct Node *current = *head;
struct Node *prev = NULL;
if (current->data == data) {
*head = current->next;
free(current);
return;
}
while (current != NULL && current->data != data) {
prev = current;
current = current->next;
}
if (current == NULL) {
return;
}
prev->next = current->next;
free(current);
}
```
以上代码分别实现了单链表的插入和删除操作。插入操作将新节点插入到链表的末尾,如果链表为空,则将新节点作为头节点;删除操作根据给定的数据值删除相应的节点,如果找到匹配的节点,则将其从链表中移除。
阅读全文