把两个链表合并成一个链表的c语言源代码
时间: 2023-06-09 14:07:41 浏览: 110
下面是将两个链表合并成一个链表的C语言源代码:
```
#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node* next;
};
void insert(struct Node** head_ref, int new_data){
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void merge(struct Node* head1, struct Node* head2, struct Node** merge_head){
struct Node* temp1 = head1;
struct Node* temp2 = head2;
struct Node* prev = NULL;
while(temp1 != NULL && temp2 != NULL){
if(temp1->data <= temp2->data){
if((*merge_head) == NULL){
(*merge_head) = temp1;
}
else{
prev->next = temp1;
}
prev = temp1;
temp1 = temp1->next;
}
else{
if((*merge_head) == NULL){
(*merge_head) = temp2;
}
else{
prev->next = temp2;
}
prev = temp2;
temp2 = temp2->next;
}
}
if(temp1 == NULL){
prev->next = temp2;
}
else{
prev->next = temp1;
}
}
void printList(struct Node* node){
while(node != NULL){
printf("%d ", node->data);
node = node->next;
}
}
int main(){
struct Node* head1 = NULL;
struct Node* head2 = NULL;
struct Node* merge_head = NULL;
insert(&head1, 7);
insert(&head1, 5);
insert(&head1, 3);
insert(&head1, 1);
insert(&head2, 8);
insert(&head2, 6);
insert(&head2, 4);
insert(&head2, 2);
merge(head1, head2, &merge_head);
printList(merge_head);
return 0;
}
```
这个源代码将两个链表head1和head2合并为一个链表merge_head。两个链表都是按递减顺序排列的。在合并的同时,它仍按递减顺序排列。
希望这个源代码可以帮助到你!
阅读全文