用c写单链表插入,删除和合并操作
时间: 2023-03-29 11:03:01 浏览: 84
可以回答这个问题。单链表插入操作可以通过以下代码实现:
```
void insert_node(struct Node* head, int val) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->val = val;
new_node->next = head->next;
head->next = new_node;
}
```
单链表删除操作可以通过以下代码实现:
```
void delete_node(struct Node* head, int val) {
struct Node* prev = head;
struct Node* curr = head->next;
while (curr != NULL) {
if (curr->val == val) {
prev->next = curr->next;
free(curr);
return;
}
prev = curr;
curr = curr->next;
}
}
```
单链表合并操作可以通过以下代码实现:
```
struct Node* merge_lists(struct Node* list1, struct Node* list2) {
struct Node* dummy = (struct Node*)malloc(sizeof(struct Node));
struct Node* tail = dummy;
while (list1 != NULL && list2 != NULL) {
if (list1->val < list2->val) {
tail->next = list1;
list1 = list1->next;
} else {
tail->next = list2;
list2 = list2->next;
}
tail = tail->next;
}
if (list1 != NULL) {
tail->next = list1;
} else {
tail->next = list2;
}
return dummy->next;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)