用c写2个链表,并归并
时间: 2023-03-29 13:02:53 浏览: 39
我可以回答这个问题。以下是示例代码:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void push(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 printList(struct Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
}
struct Node* mergeLists(struct Node* head1, struct Node* head2) {
struct Node* mergedList = NULL;
struct Node** tail = &mergedList;
while (1) {
if (head1 == NULL) {
*tail = head2;
break;
}
else if (head2 == NULL) {
*tail = head1;
break;
}
if (head1->data <= head2->data) {
*tail = head1;
head1 = head1->next;
}
else {
*tail = head2;
head2 = head2->next;
}
tail = &((*tail)->next);
}
return mergedList;
}
int main() {
struct Node* head1 = NULL;
struct Node* head2 = NULL;
push(&head1, 7);
push(&head1, 5);
push(&head1, 3);
push(&head2, 6);
push(&head2, 4);
push(&head2, 2);
printf("List 1: ");
printList(head1);
printf("\n");
printf("List 2: ");
printList(head2);
printf("\n");
struct Node* mergedList = mergeLists(head1, head2);
printf("Merged List: ");
printList(mergedList);
printf("\n");
return ;
}
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)